Triple
Time Limit: 5000/3000 MS (Java/Others) Memory Limit: 125536/65536 K (Java/Others)Total Submission(s): 1303 Accepted Submission(s): 514
Problem Description
Given many different integers, find out the number of triples (a, b, c) which satisfy a, b, c are co-primed each other or are not co-primed each other. In a triple, (a, b, c) and (b, a, c) are considered as same triple.
Input
The first line contains a single integer T (T <= 15), indicating the number of test cases.
In each case, the first line contains one integer n (3 <= n <= 800), second line contains n different integers d (2 <= d < 10 5) separated with space.
In each case, the first line contains one integer n (3 <= n <= 800), second line contains n different integers d (2 <= d < 10 5) separated with space.
Output
For each test case, output an integer in one line, indicating the number of triples.
Sample Input
1 6 2 3 5 7 11 13
Sample Output
20
Source
Recommend
ans=C(n,3) - 三个数中有一对互素的并且有一对不互素的个数sum
sum怎么算?
对于num[i],计算与之互素的元素的个数pnum,那么不互素的元素的个数就是n-1-pnum了,对于num[i]而言,不满足条件的三元组个数为pnum*(n-1-pnum)。
注意最后还要除2:比如(2, 3, 4)在处理2的时候算了一次,在处理4的时候也算了一次,但是在处理3的时候,肯定不会出现,因为对3而言,2与3互素,4也与3互素,所以总的来说每个三元组都多算了一次。
#include<stdio.h>
#include<string.h>
int gcd(int a,int b)
{
int t;
if(a<b)
{
t=a;
a=b;
b=t;
}
if(b==0)
return a;
else
return gcd(b,a%b);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,num,a[1000],i,j,sum=0,ans;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
num=0;
for(j=0;j<n;j++)
{
if(i!=j)
if(gcd(a[i],a[j])==1)
num++;
}
sum+=num*(n-num-1);
}
ans=n*(n-1)*(n-2)/6-sum/2;
printf("%d\n",ans);
}
}