Code
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 939 Accepted Submission(s): 372
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;
}
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) .
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.
Print an integer,denoting what the function returns.
Sample Input
5 1 3 4 2 4
Sample Output
64Hintgcd(x,y) means the greatest common divisor of x and y.
Source
Recommend
题解:数论
f[i]表示最大公约数为i的点对的数量
g[i]表示公约数为i的点对的数列
f[i]不好直接求解,但是g[i]可以通过枚举每个数的约数,计算得到。
我们考虑如何用g[i]推f[i]。从大到小枚举i,初始时f[i]=g[i],设j为i的约数(除去本身)f[j]-=f[i]
这个是因为如果一对数的最大公约数是i,那么他们的约数中一定包含j,f[j]表示的是最大公约数是j的,所有自然需要减去f[i]。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define N 100003
#define LL long long
#define p 10007
using namespace std;
int num[N],g[N],f[N],n,a[N];
int main()
{
freopen("gcd.in","r",stdin);
freopen("gcd.out","w",stdout);
while (scanf("%d",&n)!=EOF){
int mx=0;
memset(g,0,sizeof(g));
for (int i=1;i<=n;i++) scanf("%d",&a[i]);
for (int i=1;i<=n;i++){
int x=a[i]; mx=max(mx,x);
for (int j=1;j*j<=x;j++)
if (x%j==0) {
g[j]++;
if (x!=j*j) g[x/j]++;
}
}
for (int i=1;i<=mx;i++) g[i]=g[i]*g[i];
for (int i=mx;i>=1;i--) {
for (int j=1;j*j<=i;j++)
if (i%j==0) {
g[j]-=g[i];
if (i!=j*j&&j!=1) g[i/j]-=g[i];
}
}
LL ans=0;
for (int i=1;i<=mx;i++) ans=(ans+(LL)g[i]*(LL)i*(LL)(i-1)%p)%p;
printf("%I64d\n",ans%p);
}
}