Problem Description
In mathematics, a square number is an integer that is the square of an integer. In other words, it is the product of some integer with itself. For example, 9 is a square number, since it can be written as 3 * 3.
Given an array of distinct integers (a1, a2, …, an), you need to find the number of pairs (ai, aj) that satisfy (ai * aj) is a square number.
Input
The first line of the input contains an integer T (1 ≤ T ≤ 20) which means the number of test cases.
Then T lines follow, each line starts with a number N (1 ≤ N ≤ 100000), then N integers followed (all the integers are between 1 and 1000000).
Output
For each test case, you should output the answer of each case.
Sample Input
1
5
1 2 3 4 12
Sample Output
2
题目描述
给n个数,问有多少组两个数相乘是一个平方数.
解题思路
一个数可以分解成若干个质因数的乘积,所以思路就是将每个数尽量分解质因数,然后相同的余数中任意组合.
这里在质因子打表的时候直接标记质因子平方,按照质因子的平方分解,再统计余数.
代码实现
#include<bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);\
cin.tie(0);\
cout.tie(0);
typedef long long ll;
const int maxn = 1e6+7;
const int maxl = (int)sqrt(maxn);
int num[207];
bool vis[maxl];
int mark[maxn];
int countt=0;
void init()
{
for(int i=2; i<maxl; i++)
{
if(!vis[i])
{
num[countt++]=i*i;
for(int j=i*i; j<maxl; j+=i)
vis[j]=1;
}
}
}
int main()
{
IO;
init();
int T;
cin>>T;
while(T--)
{
memset(mark,0,sizeof(mark));
int n,t;
cin>>n;
for(int i=0; i<n; i++)
{
cin>>t;
for(int j=0; num[j]<=t&&j<countt; j++)
{
while(t%num[j]==0)
t/=num[j];
}
mark[t]++;
}
ll ans=0;
for(int i=0; i<maxn; i++)
{
if(mark[i])
ans+=mark[i]*(mark[i]-1)/2;
}
cout<<ans<<endl;
}
return 0;
}