问题:
Given the value of N, you will have to find the value of G. The definition of G is given below:
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
题意:给定 n(1<n≤4000000),请你计算下面式子的值: ![](https://i-blog.csdnimg.cn/blog_migrate/a22d3c12f35f7e8b72775f4d23b11e3a.png)
思路:设f(n)=gcd(1 ,n)+gcd(2 ,n)+gcd(3 ,n)+...+gcd(n-1, ,n),则所求答案为S(n)=f(2)+f(3)+...f(n) 。只需求出f(n) , 就可以递推出所有答案: S(n)=S(n-1)+f(n) 。因此,本题的重点在于如何计算f(n) 。注意到所有gcd(x,n)的值都是n 的约数,可以按照这个约数进行分类,用g(n, i)表示满足gcd(x,n)=i 且x<n 的正整数x 的个数,则f(n)=sum{ i × g(n, i) | i 是n 的约数}。注意到gcd(x,n)=i的充要条件是gcd(x/i,n/i)=1(此时x/i和n/i互质), 因此满足条件的x/i 有phi(n/i)个,说明g(n ,i)=phi(n/i) 。问题到这里还没有结束。如果依次计算j例,需要对每个n 枚举它的约数i , 速度较慢,但如果把思路逆转过来,对于每个i 枚举它的倍数n (并且更新j(n) 的值) ,时间复杂度将降为与素数筛法同阶。
代码:
#include<stdio.h> #include<string.h> int n; long long phi[4000005],s[4000005],f[4000005]; int main() { phi[1]=1; for (int i=2; i<4000005; i++) if (!phi[i]) for (int j=i; j<4000005; j+=i) { if (!phi[j]) phi[j]=j; phi[j]=phi[j]/i*(i-1); } for (int i=1; i<4000005; i++) for (int j=i*2; j<4000005; j+=i) f[j]+=phi[j/i]*i; s[2]=f[2]; for(int i=3; i<4000005; i++) s[i]=s[i-1]+f[i]; while(~scanf("%d",&n)&&n) printf("%lld\n",s[n]); return 0; }