Ultraviolet A 11426-GCD-extreme (II)
Question Link
Question: Given N, ask ΣI<=NI= 1 sigmaJ<NJ= 1GCD(I,J.
Idea: for example in the lrj White Book, set F (n) = gcd (1, N) + gcd (2, n) +... + gcd (n-1, n ). in this way, the recursive formula S (n) = F (2) + f (3) +... + f (n) => S (n) = S (n-1) + f (n );.
In this case, the question becomes how to calculate F (n ). set g (n, I) to meet the number of gcd (x, n) = I, F (n) = sum {I * g (n, I )}. then the problem is transformed into how to calculate g (n, I), gcd (x, n) = the condition that I meet is gcd (x/I, n/I) = 1, therefore, as long as the Euler's function PHI (N/I) is obtained, we can obtain the number of interclasses with x/I, and then obtain the number of gcd (x, n) = I, in this way, we can solve the problem.
Code:
#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;}