山东省第六届ACM竞赛 山东理工SDUT3258 Square Number

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值