# HDU5072 coprime

## Coprime

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 2952 Accepted Submission(s): 1142

Problem Description
There are n people standing in a line. Each of them has a unique id number.

Now the Ragnarok is coming. We should choose 3 people to defend the evil. As a group, the 3 people should be able to communicate. They are able to communicate if and only if their id numbers are pairwise coprime or pairwise not coprime. In other words, if their id numbers are a, b, c, then they can communicate if and only if [(a, b) = (b, c) = (a, c) = 1] or [(a, b) ≠ 1 and (a, c) ≠ 1 and (b, c) ≠ 1], where (x, y) denotes the greatest common divisor of x and y.

We want to know how many 3-people-groups can be chosen from the n people.

Input
The first line contains an integer T (T ≤ 5), denoting the number of the test cases.

For each test case, the first line contains an integer n(3 ≤ n ≤ 105), denoting the number of people. The next line contains n distinct integers a1, a2, … , an(1 ≤ ai ≤ 105) separated by a single space, where ai stands for the id number of the i-th person.

Output
For each test case, output the answer in a line.

Sample Input
1
5
1 3 9 10 2

Sample Output
4

Source
2014 Asia AnShan Regional Contest

 这道题并没有太多算法包含在里面，但是很考验人的思维。
首先看这道题的题面，就是要求所有的三元组，满足两两都互质或者两两都不互质。乍一看这题的条件确实有点麻烦，而且数据范围在10的五次方内，一般来说这个数据范围都是nlogn的解法，显然这题也差不多如此。
下面介绍一下这题的具体做法，考虑答案的成立条件是两两互质或不互质，那么他们的不成立条件便是有一对不互质和一对互质，于是我们就考虑不成立的情况，再用C（n,3)减去，就是我们要的答案。
枚举一个数，再算出每一个数所不互质和互质的数，在这里我们采用分解每个数的质因子，再通过枚举质因子来计算不互质的数i，n-i-1便是互质的数，具体还要用到容斥原理。

/*
ID: Rec
PROG: test
LANG: C++
*/
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#include<algorithm>
#include<stack>
#define N 100005
typedef long long LL;
int T,n,num[N],has[N],prime[N],prim,cnt[N][20];
int ext[N];
LL ans;
bool isprime[N];
void init(){
isprime[0]=1;isprime[1]=1;
for (int i=2;i<N;i++)
if (!isprime[i]){
prime[++prim]=i;
for (int j=2*i;j<=N;j+=i)isprime[j]=1;
}
}
void getfactor(){
for (int i=2;i<=N;i++){
int m=i;
for (int j=1;j<=prim;j++){
if (!isprime[m]){
cnt[i][++cnt[i][0]]=m;
break;
}
if (m%prime[j]==0){
cnt[i][++cnt[i][0]]=prime[j];
while (m%prime[j]==0)m/=prime[j];
}
}
}
}
void extend(){
memset(ext,0,sizeof(ext));
for (int i=1;i<N;i++)
for (int j=i;j<N;j+=i)
if (has[j])++ext[i];
}
LL solve(){
LL sum=0;
for (int i=1;i<=n;i++){
int x=num[i];
if (x==1)continue;
LL col=0;
for (int j=(1<<cnt[x][0])-1;j;j--){
bool b=0;
int mul=1;
for (int k=1;k<=cnt[x][0];k++)
if (1<<(k-1)&j){
b^=1;
mul*=cnt[x][k];
}
if (b)col+=(ext[mul]-1);
else col-=(ext[mul]-1);
}
sum+=col*(n-col-1);
}
return sum;
}
int main(){
freopen("hdu5072.in","r",stdin);
freopen("hdu5072.out","w",stdout);
scanf("%d",&T);
init();
getfactor();
while (T--){
scanf("%d",&n);
memset(has,0,sizeof(has));
for (int i=1;i<=n;i++){
int x;
scanf("%d",&x);
has[x]=1;
num[i]=x;
}
extend();
ans=(LL)n*(n-1)*(n-2)/6-solve()/2;
printf("%lld\n",ans);
}
return 0;
}