题目描述
给出n,求所有gcd(i,j)之和,其中1<=i<j<=n. 不超过20000组数据,n<=1000000.
输入格式
The input file contains at most 20000 lines of inputs. Each line contains an integer N (1 < N < 1000001). The meaning of N is given in the problem statement. Input is terminated by a line containing a single zero.
输出格式
For each line of input produce one line of output. This line contains the value of G for the corresponding N. The value of G will fit in a 64-bit signed integer.
输入输出样例
输入 #1 复制
10
100
200000
0
输出 #1 复制
67
13015
143295493160
不同数据范围不同算法,这里只有n,那么
g ( n ) = ∑ i = 1 n − 1 g c d ( i , n ) g(n)=\sum_{i=1}^{n-1}{\rm gcd}(i,n) g(n)=∑i=1n−1gcd(i,n)
那么答案就是:
∑ i = 1 n g ( n ) \sum_{i=1}^{n}g(n) ∑i=1ng(n)
现在我们逐步化简:
g ( n ) = ∑ i = 1 n − 1 g c d ( i , n ) = ∑ d ∣ n d × ∑ i = 1 n − 1 [ g c d ( i , n ) = d ] = ∑ d ∣ n d × ∑ i = 1 n d − 1 [ g c d ( i , n d ) = 1 ] = ∑ d ∣ n d × φ ( n d ) \begin{aligned}g(n)&=\sum_{i=1}^{n-1}{\rm gcd}(i,n)\\&=\sum_{d|n}d\times\sum_{i=1}^{n-1}[{\rm gcd}(i,n)=d]\\&=\sum_{d|n}d\times\sum_{i=1}^{\frac{n}{d}-1}[{\rm gcd}(i,\frac{n}{d})=1]\\&=\sum_{d|n}d\times\varphi\left(\frac{n}{d}\right)\end{aligned} g(n)=i=1∑n−1gcd(i,n)=d∣n∑d×i=1∑n−1[gcd(i,n)=d]=d∣n∑d×i=1∑dn−1[gcd(i,dn)=1]=d∣n∑d×φ(dn)
再埃氏筛一下就好了
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cstdio>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<cmath>
#include<map>
#include<set>
using namespace std;
const int inf=0x7fffffff;
const double eps=1e-10;
const double pi=acos(-1.0);
inline int read(){
int x=0,f=1;char ch;ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-') f=0;ch=getchar();}
while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch&15);ch=getchar();}
if(f)return x;else return -x;
}
const int N=1000010;
bool vis[N];
long long prim[N],phi[N],ans[N];
void get_phi(int n){
phi[1]=0;
for(int i=2;i<=n;i++){
if(!vis[i]){phi[i]=i-1;prim[++prim[0]]=i;}
for(int j=1;j<=prim[0]&&i*prim[j]<=n;j++){
vis[i*prim[j]]=1;
if(i%prim[j]==0){phi[i*prim[j]]=phi[i]*prim[j];break;}
else phi[i*prim[j]]=phi[i]*(prim[j]-1);
}
}
for(int i=1;i<=n;i++)ans[i]=phi[i];
for(int i=2;i*i<=n;i++){
ans[i*i]+=phi[i]*i;
for(int j=i+1;j*i<=n;j++)
ans[j*i]+=phi[i]*j+phi[j]*i;
}
ans[1]=0;
for(int i=2;i<=n;i++)ans[i]+=ans[i-1];
}
int n;
int main(){
get_phi(1000000);
while(scanf("%d",&n)==1&&n){printf("%lld\n",ans[n]);}
return 0;
}