题目链接:点击这里
题目大意:
给定正整数
n
(
1
<
n
<
2
31
−
1
)
n(1<n<2^{31}-1)
n(1<n<231−1) ,求:
∑
i
=
1
n
gcd
(
i
,
n
)
\sum_{i=1}^n\gcd(i,n)
i=1∑ngcd(i,n)
题目分析:
∑
i
=
1
n
gcd
(
i
,
n
)
\sum_{i=1}^n\gcd(i,n)
i=1∑ngcd(i,n)
=
∑
d
∣
n
∑
i
=
1
n
[
gcd
(
i
,
n
)
=
d
]
⋅
d
=\sum_{d|n}\sum_{i=1}^n[\gcd(i,n)=d]·d
=d∣n∑i=1∑n[gcd(i,n)=d]⋅d
=
∑
d
∣
n
d
∑
i
=
1
n
/
d
[
gcd
(
i
/
d
,
n
/
d
)
=
1
]
=\sum_{d|n}d\sum_{i=1}^{n/d}[\gcd(i/d,n/d)=1]
=d∣n∑di=1∑n/d[gcd(i/d,n/d)=1]
=
∑
d
∣
n
d
⋅
φ
(
n
/
d
)
=\sum_{d|n}d·\varphi(n/d)
=d∣n∑d⋅φ(n/d)
所以我们就可以枚举
n
n
n 的因子然后暴力求欧拉函数值即可,时间复杂度看似为
O
(
n
)
O(n)
O(n) ,但是由于求欧拉函数时的质因子分解跑不满根号,所以时间复杂度为
O
(
可
过
)
O(可过)
O(可过)
具体细节见代码:
// Problem: Longge's problem
// Contest: Virtual Judge - POJ
// URL: https://vjudge.net/problem/POJ-2480
// Memory Limit: 65 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
//#pragma GCC optimize(2)
//#pragma GCC optimize("Ofast","inline","-ffast-math")
//#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
// #include<unordered_map>
#define ll long long
#define inf 0x3f3f3f3f
#define Inf 0x3f3f3f3f3f3f3f3f
//#define int ll
#define endl '\n'
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;
int read()
{
int res = 0,flag = 1;
char ch = getchar();
while(ch<'0' || ch>'9')
{
if(ch == '-') flag = -1;
ch = getchar();
}
while(ch>='0' && ch<='9')
{
res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
ch = getchar();
}
return res*flag;
}
const int maxn = 1e6+5;
const int mod = 1e9+7;
const double pi = acos(-1);
const double eps = 1e-8;
ll n;
ll get_phi(int n)
{
ll res = n;
for(ll i = 2;i*i <= n;i++)
{
if(n%i) continue;
res = res/i*(i-1);
while(n%i == 0) n /= i;
}
if(n > 1) res = res/n*(n-1);
return res;
}
int main()
{
while(~scanf("%lld",&n))
{
ll res = 0;
for(ll i = 1;i*i <= n;i++)
{
if(n%i == 0)
{
res += i*get_phi(n/i);
if(i*i != n) res += (n/i)*get_phi(i);
}
}
printf("%lld\n",res);
}
return 0;
}