Given the value of N, you will have to findthe value of G. The definition of G is given below:
Here
For those who have trouble understandingsummation notation, the meaning of G is given in the followingcode:
G=0; for(i=1;i<N;i++) for(j=i+1;j<=N;j++) { } |
Input
The input file contains at most 100 lines ofinputs. Each line contains an integer N(1<N<4000001)
Output
For each line of input produce one line ofoutput. This line contains the value of G for the corresponding N.The value of G will fit in a 64-bit signed integer.
SampleInput
10
100
200000
0
Output for SampleInput
67
13015
143295493160
题意:求对于每个i<=N,求f(i)=GCD(1,i)+GCD(2,i)+......GCD(i-1,i)并求前N项和。
对于一个N,设GCD(a,N)=b;则有N=b*x,a=b*y,GCD(a/b,N/b)=1即GCD(x,y)=1;
又依题意得a<N,则Y<X,则满足GCD(a,N)=b且a<N的a的个数等于GCD(y,x)=1且y<x的y的个数,即eluer(x)(小于x且与x互质的数的个数)
因此打个欧拉表再枚举N的约数b即可
代码:
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<sstream>
#include<algorithm>
#include<utility>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<math.h>
#include<iterator>
#include<stack>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const double eps=1e-8,PI=3.1415926538;
const LL MOD=1000000000+7;
const LL MAXN=4000007;
LL m[MAXN],phi[MAXN],p[MAXN],pt;
void make()
{
phi[1]=1;
LL N=MAXN;
LL k;
for(int i=2;i<N;i++)
{
if(!m[i])
p[pt++]=m[i]=i,phi[i]=i-1;
for(int j=0;j<pt&&(k=p[j]*i)<N;j++)
{
m[k]=p[j];
if(m[i]==p[j])
{
phi[k]=phi[i]*p[j];
break;
}
else
phi[k]=phi[i]*(p[j]-1);
}
}
}
LL gcd(LL a,LL b)
{
if(b==0)return a;
else return gcd(b,a%b);
}
LL S[MAXN];
int main()
{
make();
phi[1]=phi[0]=0;
memset(S,0,sizeof(S));
LL z=sqrt(MAXN);
for(int i=1;i<=z;i++)//枚举N的约数
{
for(int j=2;j*i<=MAXN-3;j++)//N=i*j
{
S[j*i]+=i*phi[j];
if(z<j)S[j*i]+=j*phi[i];//z<span style="font-family:Courier New;"><j时,i*j的约数j枚举不到</span>
}
}
LL N,G;
while(scanf("%lld",&N)!=-1&&N!=0)
{
G=0;
for(int i=2;i<=N;i++)
{
G+=S[i];
}
printf("%lld\n",G);
}
return 0;
}