HDU5072 Coprime【容斥原理】

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 ≤ 10 5), denoting the number of people. The next line contains n distinct integers a 1, a 2, . . . , a n(1 ≤ a i ≤ 10 5) separated by a single space, where a i 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

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=1e5+10;
int cnt[N],a[N],pri[500],nu;
LL solve(int n)
{
if(n==1)return LL(0);
LL ret=-1;
nu=0;
for(int i=2;i*i<=n;i++)
{
if(n%i==0)
{
pri[nu++]=i;
while(n%i==0)n/=i;
}
}
if(n!=1)pri[nu++]=n;
int tim=1<<nu;
int tem,num;
for(int i=1;i<tim;i++)
{
tem=1;
num=0;
for(int j=0;j<nu;j++)
{
if(i&(1<<j))
{
num++;
tem*=pri[j];
}
}
if(num&1)
ret+=cnt[tem];
else
ret-=cnt[tem];
}
return ret;
}
int main()
{
int TA,n,x,tem;
scanf("%d",&TA);
while(TA--)
{
LL sum=0,ans,res;
scanf("%d",&n);
memset(cnt,0,sizeof(cnt));
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
for(int i=1;i<=n;i++)
{
x=a[i];
nu=0;
for(int j=2;j*j<=x;j++)
{
if(x%j==0)
{
pri[nu++]=j;
while(x%j==0)x/=j;
}
}
if(x!=1)pri[nu++]=x;
int tim=1<<nu;

for(int k=1;k<tim;k++)
{
tem=1;
for(int j=0;j<nu;j++)
{
if(k&(1<<j))
tem*=pri[j];
}
cnt[tem]++;
}
}
//for(int i=1;i<=20;i++)cout<<i<<" "<<cnt[i]<<endl;
for(int i=1;i<=n;i++)
{
//cout<<"  &&";

res=solve(a[i]);
sum+=res*(n-res-1);
}

sum/=2;
ans=(LL)n*((LL)n-1)*(n-2)/3/2;
ans=ans-sum;
printf("%lld\n",ans);
}
}