Triple
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 assame 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 < 105) 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
解法
这是一道杭电ACM上面的题。
计算三个数中两两互质或者不互质的三元组个数,等价于总数-三个中两个互质且两个不互质的情况,总数记为sum=n*(n-1*(n-2))。
三个中两个互质且两个不互质的情况,即计算第i个数与多少个数互质,记为c1,与多少个数不互质,记为c2,cnt是每个数c1*c2的和,然后解为(sum/6-cnt/2)。
AC代码
#include <string.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int a[1000],sum;
int gcd(int a, int b)//递归辗转相除法求最大公约数
{
if (b == 0)return a;
return gcd(b, a%b);
}
int main()
{
int T;
cin >> T;
while (T--)
{
int n,c1,c2,cnt=0;
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
sum=n*(n-1)*(n-2);
for (int i = 1; i <=n; i++)
{
c1 = 0, c2 = 0;
for (int j = 1; j <= n; j++)
if(i!=j)
{
if (gcd(a[i], a[j]) == 1)//互质
c1++;
else //不互质
c2++;
}
cnt += c1*c2;
}
printf("%d\n", sum / 6 - cnt/2);
}
return 0;
}