FZU1969(最大公约数之和)

来源:互联网 发布:业务员销售软件 编辑:程序博客网 时间:2024/06/11 06:41

题目:GCD Extreme

 

题意:

Given the value of N, you will have to find the value of G. The meaning of G is given in the following code

G=0;
for(i=1;i<N;i++)  
    for(j=i+1;j<=N;j++)
      G+=gcd(i,j);

 

sqrt(n)的算法:

 

#include<iostream>#include<cstdio>using namespace std;#define maxn 1000005#define LL __int64int phi[maxn];LL ans[maxn];void Init(){int i,j,k;for(i=2;i<maxn;i++) phi[i]=i;for(i=2;i<maxn;i++)if(phi[i]==i)for(j=i;j<maxn;j+=i)phi[j]=phi[j]/i*(i-1);for(i=2;i<maxn;i++)ans[i]=phi[i];for(i=2;i<=1000;i++){ans[i*i]+=phi[i]*i;for(j=i*i+i,k=i+1;j<maxn;j+=i,k++)ans[j]+=i*phi[k]+k*phi[i]; }for(i=1;i<maxn;i++)ans[i]+=ans[i-1];}int main(){Init();int n;while(scanf("%d",&n),n)printf("%I64d\n",ans[n]);return 0;}