5 1 3 4 2 4
64Hintgcd(x,y) means the greatest common divisor of x and y.
同样显然的是,对于两个数,如果他们都是 x 的倍数,那么他们的 gcd 一定也是 x 的倍数。
所以,我们求出 x 的倍数在数列中有 k 个,然后就有 k^2 对数满足两个数都是 x 的倍数,这 k^2 对数的 gcd,要么是 x ,要么是 2x, 3x, 4x...
并且,一个数是 x 的倍数的倍数,它就一定是 x 的倍数。所以以 x 的倍数为 gcd 的数对,一定都包含在这 k^2 对数中。
如果我们从大到小枚举 x ,这样计算 x 的贡献时,x 的多倍数就已经计算完了。我们用 f(x) 表示以 x 为 gcd 的数对个数。
那么 f(x) = k^2 - f(2x) - f(3x) - f(4x) ... f(tx) (tx <= 10000, k = Cnt[x])
这样枚举每个 x ,然后枚举每个 x 的倍数,复杂度用调和级数计算,约为 O(n logn)。
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int MaxN = 1e4 + 10;
const int Mod = 10007;
int cnt[MaxN], F[MaxN];
int main() {
int n, a;
while(~scanf("%d", &n)) {
memset(cnt, 0, sizeof(cnt));
for(int i = 0; i < n; i++) {
scanf("%d", &a);
for(int j = 1; j * j <= a; j++) {
if(a % j == 0) {
cnt[j]++;
if(j * j != a)
cnt[a / j]++;
}
}
}
int ans = 0;
for(int i = 10000; i >= 1; i--) {
F[i] = cnt[i] * cnt[i] % Mod;
for(int j = i * 2; j <= 10000; j += i)
F[i] = (F[i] - F[j] + Mod) % Mod;
int p = i * (i - 1) % Mod;
ans = (ans + p * F[i] % Mod) % Mod;
}
printf("%d\n", ans);
}
return 0;
}原文地址:http://blog.csdn.net/lyhvoyage/article/details/45306211