Code
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 209 Accepted Submission(s): 85
Problem Description
WLD likes playing with codes.One day he is writing a function.Howerver,his computer breaks down because the function is too powerful.He is very sad.Can you help him?
The function:
int calc
{
int res=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
res+=gcd(a[i],a[j])*(gcd(a[i],a[j])-1);
res%=10007;
}
return res;
}
Input
There are Multiple Cases.(At MOST
10)
For each case:
The first line contains an integer N(1≤N≤10000).
The next line contains N
integers a1,a2,...,aN(1≤ai≤10000).
Output
For each case:
Print an integer,denoting what the function returns.
Sample Input
5 1 3 4 2 4
Sample Output
64 Hint gcd(x,y) means the greatest common divisor of x and y.
Source
题意: 简单易懂,就给你一段代码,叫你优化;
题解: 莫比乌斯反演, 首先我们设f(d)表示在给出的所有数中有f(d)对最大公约数是d. cnt(n) 表示在给出的所有数中有cnt(n)个是n的倍数(包含n). 假设我们已经知道了这两个函数,然后就可以用莫比乌斯反演做了. 首先F(n) = cnt(n) * cnt(n); 表示大于等于n的所有数组成的对数,那么有F(n) = f(n) + f(n * 2) + f(n * 3) + .....f(max);
做完以上步骤,就可以套用莫比乌斯反演做了.
莫比无私反演的公式在bin神的博客上有,去搬吧! 啊啊啊啊啊啊啊啊啊啊啊!!!!!!!!!!!!
AC代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MAXN = 1e4; typedef long long ll; const int mod = 10007; bool check[MAXN + 10]; ll prime[MAXN + 10],cnt[MAXN + 10]; ll mu[MAXN + 10],F[MAXN + 10]; void Moblus() { memset(check,false,sizeof(check)); mu[1] = 1; int tot = 0; for(int i = 2; i <= MAXN; i++) { if(!check[i]) { prime[tot++] = i; mu[i] = -1; } for(int j = 0; i * prime[j] <= MAXN; j++) { check[i * prime[j]] = true; if(i % prime[j] == 0) { mu[i * prime[j]] = 0; break; } mu[i * prime[j]] = -mu[i]; } } } int main() { //freopen("in","r",stdin); Moblus(); int n,x; while(~scanf("%d",&n)) { memset(cnt,0,sizeof(cnt)); for(int i = 0; i < n; i++) { scanf("%d",&x); cnt[x]++; } for(int i = 1; i <= MAXN; i++) for(int j = i * 2; j <= MAXN; j += i) cnt[i] += cnt[j]; for(int i = 1; i <= MAXN; i++) F[i] = cnt[i] * cnt[i]; ll res = 0; for(int i = 1; i <= MAXN; i++) { ll tp = 0; for(int j = i; j <= MAXN; j += i) { tp += mu[j / i] * F[j]; if(tp >= mod) tp %= mod; } res += tp * i % mod * (i - 1); if(res >= mod) res %= mod; } printf("%I64d\n",res); } return 0; }