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.
Example Input
1 5 1 2 3 4 12
Example Output
2
思路:唯一分解定理:任何一个大于1的数,都可以拆分成若干素数的乘积。
有了这个定理再看题目要求可知,平方数就一定能表示为若干素数的偶次幂的乘积。
所以枚举所有的素因子,如果出现偶次幂,忽略,如果是奇次幂就记录在对于的位置factor[ n ]++。
最后统计有多少个可以配对的因数就行了。
#include <cstdio> #include <cstring> #include <cmath> #include <iostream> using namespace std; int num[100005]; int prime[1000005],re[1000005],fac[1000005]; int main(){ int t,n,top=-1; long long result; scanf("%d",&t); memset(prime,0,sizeof(prime)); prime[0]=prime[1]=1; for(int i=2;i<=sqrt(1000005);i++){ if(prime[i]==0){ re[++top]=i; for(int j=i+i;j<1000005;j+=i){ prime[j]=1; } } } while(t--){ scanf("%d",&n); memset(fac,0,sizeof(fac)); result=0; for(int i=1;i<=n;i++){ scanf("%d",&num[i]); int m=num[i],ans=1; for(int j=0;j<=top&&m>1;j++){ int times=0; while(m%re[j]==0){ times++; m/=re[j]; } if(times&1){ ans*=re[j]; } if(prime[m]==0){//优化 否则会超时 ans*=m; break; } } result+=fac[ans]; fac[ans]++; } printf("%lld\n",result); } return 0; }