GCD - Extreme (II) UVA - 11426
Given the value of N, you will have to find the value of G. The definition of G is given below:
G =
∑i<Ni=1∑j<=Nj=i+1
∑
i
=
1
i
<
N
∑
j
=
i
+
1
j
<=
N
GCD(i,j)
Input
The input file contains at most 100 lines of inputs. Each line contains an integer N (1 < N < 4000001).
The meaning of N is given in the problem statement. Input is terminated by a line containing a single
zero.
Output
For each line of input produce one line of output. This line contains the value of G for the correspondingN. The value of G will fit in a 64-bit signed integer.
Sample Input
10
100
200000
0
Sample Output
67
13015
143295493160
题意:
给定N,求所给公式的值
分析:
由给出到公式,我们设
f(n)=gcd(1,n)+gcd(2,n)+gcd(3,n)+......+gcd(n−1,n)
f
(
n
)
=
g
c
d
(
1
,
n
)
+
g
c
d
(
2
,
n
)
+
g
c
d
(
3
,
n
)
+
.
.
.
.
.
.
+
g
c
d
(
n
−
1
,
n
)
同理
f(n−1)=gcd(1,n)+gcd(2,n)+...+gcd(n−2,n−1)
f
(
n
−
1
)
=
g
c
d
(
1
,
n
)
+
g
c
d
(
2
,
n
)
+
.
.
.
+
g
c
d
(
n
−
2
,
n
−
1
)
.
.
.
f(2)=gcd(1,2)
f
(
2
)
=
g
c
d
(
1
,
2
)
所以公式求和
G=S(n)=f(2)+f(3)+...+f(n)
G
=
S
(
n
)
=
f
(
2
)
+
f
(
3
)
+
.
.
.
+
f
(
n
)
所以我们到任务变成求
f(n)
f
(
n
)
为了便于说明我们再设一个变量叫
g(n,j)⟶
g
(
n
,
j
)
⟶
满足
gcd(x,n)=j
g
c
d
(
x
,
n
)
=
j
到个数,其中x是[1,n]的数
↓
↓
gcd(xj,nj)=1
g
c
d
(
x
j
,
n
j
)
=
1
,问题再次简化,设
i=nj
i
=
n
j
,我们只要找到i以内和i互质到个数即可,这样我们枚举倍数j只要i×j < n 即可,而这个倍数就是上面到最大公因数。
这样我们就相当于知道了和n公因数为j到个数一乘便是和即
f(n)=∑(j⋅g(n,j))
f
(
n
)
=
∑
(
j
⋅
g
(
n
,
j
)
)
求一个数以内互质到个数用欧拉函数即可
code:
#include <bits/stdc++.h>
using namespace std;
const int N = 4e6+10;
typedef long long ll;
int phi[N];
ll f[N];
void getphi(){
for(int i = 1; i < N; i++) phi[i] = i;
for(int i = 2; i < N; i++){
if(phi[i] == i){
for(int j = i; j < N; j += i){
phi[j] = phi[j] / i * (i - 1);
}
}
for(int j = 1; j * i < N; j++){
f[j*i] += j * phi[i];
}
}
}
int main(){
getphi();
int n;
while(cin >> n && n){
ll ans = 0;
for(int i = 1; i <= n; i++){
ans += f[i];
}
printf("%lld\n",ans);
}
return 0;
}