标签:style blog http color get width
题意:给定N,求∑i<=ni=1∑j<nj=1gcd(i,j)的值。
思路:lrj白书上的例题,设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),表示满足gcd(x, n) = i的个数,这样f(n) = sum{i * g(n, i)}. 那么问题又转化为怎么求g(n, i),gcd(x, n) = i满足的条件为gcd(x / i, n / i) = 1,因此只要求出欧拉函数phi(n / i),就可以得到与x / i互质的个数,从而求出gcd(x , n) = i的个数,这样整体就可以求解了
代码:
#include <stdio.h> #include <string.h> const int N = 4000005; int n; long long phi[N], s[N], f[N]; int main() { phi[1] = 1; for (int i = 2; i < N; i++) { if (phi[i]) continue; for (int j = i; j < N; j += i) { if (!phi[j]) phi[j] = j; phi[j] = phi[j] / i * (i - 1); } } for (int i = 1; i < N; i++) { for (int j = i * 2; j < N; j += i) { f[j] += phi[j / i] * i; } } s[2] = f[2]; for (int i = 3; i < N; i++) s[i] = s[i - 1] + f[i]; while (~scanf("%d", &n) && n) { printf("%lld\n", s[n]); } return 0; }
UVA 11426 - GCD - Extreme (II) (数论),布布扣,bubuko.com
UVA 11426 - GCD - Extreme (II) (数论)
标签:style blog http color get width
原文地址:http://blog.csdn.net/accelerator_/article/details/35306227