Given the value of N, you will have to find the value of G. The definition of G is given below: i< N j≤N
G= GCD(i,j) i=1 j=i+1
Here GCD(i,j) means the greatest common divisor of integer i and integer j.
For those who have trouble understanding summation notation, 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);
}
/*Here gcd() is a function that finds
the greatest common divisor of the two
input numbers*/
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 corresponding N. The value of G will fit in a 64-bit signed integer.
Sample Input
10
100
200000
0
Sample Output
67
13015
143295493160
解释来自:http://blog.csdn.net/u011639256/article/details/41382879
我们令f(n) = gcd(1, n) + gcd(2, n) + … + gcd(n-1, n)
则对应的结果s(n) = f(2) + f(3) + … + f(n)
所以s(n) = s(n-1)+f(n)
因此我们只需求出所有的f(n),在递推即可
取g(n, i)表示小于n且与n的gcd值等于i的数x的个数(gcd(n, x) = i)
则f(n) = 1*gcd(n, 1) + 2*gcd(n ,2) + …
而gcd(n, x) = i即gcd(n/i, x/i) = 1
所以g(n, i) == phi(n/i)
另外用线性筛预处理了欧拉函数的值。
#include "cstring"
#include "cstdio"
#include "string.h"
#include "iostream"
using namespace std;
#define Max 4000005
int euler[Max];
long long ans[Max];
void Init(){
euler[1]=1;
for(int i=2;i<Max;i++)
euler[i]=i;
for(int i=2;i<Max;i++)
if(euler[i]==i)
for(int j=i;j<Max;j+=i)
euler[j]=euler[j]/i*(i-1);
}
long long f[Max],s[Max];
void gao()
{
ans[1]=1;
memset(ans,0,sizeof(ans));
for(int i=1;i<Max;i++)
for(int n=i*2;n<Max;n+=i)
f[n]+=i*euler[n/i];
s[2]=f[2];
for(int n=3;n<Max;n++)
s[n]=s[n-1]+f[n];
}
int main()
{
int n;
Init();
gao();
while(~scanf("%d",&n)&&n)
{
printf("%lld\n",s[n]);
}
}