Given the value of N, you willhave 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 troubleunderstanding summation 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++) { 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 100lines of inputs. Each line contains an integer N (1<N<4000001). Themeaning of N is given in the problem statement. Input is terminated by a linecontaining a single zero.
Output
For each lineof input produce one line of output. This line contains the value of G for thecorresponding N. The value of G will fit in a 64-bit signed integer.
Sample Input Output for SampleInput
10 100 200000 0
|
67 13015 143295493160
|
Problemsetter: Shahriar Manzoor
SpecialThanks: Syed Monowar Hossain
题意:输入正整数n,求gcd(1, 2)+gcd(1, 3)+gcd(2, 3)+...+gcd(n-1, n),即全部满足1<=i<j<=n的数对(i, j)所相应的gcd(i,j)之和。
思路:设f(n) = gcd(1, n)+gcd(2, n) + ...+gcd(n-1, n),则答案就为S(n) = f(2)+f(3)+...+f(n),仅仅需求出f(n),就能够递推出答案:S(n) = S(n-1) + f(n),
我们再用g(n,i)表示满足gcd(x, n)=i且x<n的正整数x的个数,则f(n)=sum{i*g(n, i)}, 注意到gcd(x, n) = i的充要条件是gcd(x/i, n/i) = 1,因此满足条件的有x/i有phi(n/i),
phi(a) 表示的是不超过x且和x互素的整数个数,我们通过类似筛选法的方法。每次去更新某个数i的倍数。而不是去枚举每一个n的约数。
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> typedef long long ll; using namespace std; const int maxn = 4000001; int phi[maxn]; ll S[maxn], f[maxn]; void phi_table(int n) { for (int i = 2; i <= n; i++) phi[i] = 0; phi[1] = 1; for (int i = 2; i <= n; i++) if (!phi[i]) for (int j = i; j <= n; j += i) { if (!phi[j]) phi[j] = j; phi[j] = phi[j] / i * (i-1); } } int main() { phi_table(maxn); memset(f, 0, sizeof(f)); for (int i = 1; i <= maxn; i++) for (int n = i*2; n <= maxn; n += i) f[n] += i * phi[n/i]; S[2] = f[2]; for (int n = 3; n <= maxn; n++) S[n] = S[n-1] + f[n]; int n; while (scanf("%d", &n) != EOF && n) printf("%lld ", S[n]); return 0; }
版权声明:本文博主原创文章。博客,未经同意不得转载。