SDUT 3258 Square Number(2015年山东省第六届ACM大学生程序设计竞赛)

本文介绍了一个算法问题,即在给定整数数组中找到两数乘积为平方数的所有不同组合。通过分解质因数的方法,文章提供了一种有效的解决方案,并附带了完整的C语言实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Square Number

Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

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.
 

输入

 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).
 

输出

 For each test case, you should output the answer of each case.

示例输入

1   
5   
1 2 3 4 12

示例输出

2


分析:

判断两个数的乘积是否为平方数,需要先将该数字拆分多个素数的平方数的形式,例如:

12 = 2*2*3

3 = 3

这样2*2就可以忽略不看,因为它已经是平方数,只需要找3与12的质因数3配成平方数即可.

先打一个1000的素数表,因为最大数据是1e6,所以取根号大小就行。然后根据素数表打一个平方数表。

代码如下:

#include <stdio.h>
#include <string.h>
#define MAX 1000010
int pri[1010];
int dp[200];
int vis[MAX];
int amount=0;
void init()
{
	for(int i=2;i<=1000;i++)
	{//素数打表 
		for(int j=i+i;j<=1000;j+=i)
		{
			if(!pri[j])
				pri[j]=1;
		}
	}
	//平方数打表 
	for(int i=2;i<=1000;i++)
		if(!pri[i])
			dp[amount++]=i*i;
}

int main()
{
	int T,n;
	int t;
	int i,j;
	init();
	scanf("%d",&T);
	while(T--)
	{
		memset(vis,0,sizeof(vis));
		int ans=0;
		scanf("%d",&n);
		for(i=0;i<n;i++)
		{
			scanf("%d",&t);
			for(j=0;j<amount;j++)
			{
				if(t%dp[j]==0)
				{
					while(t%dp[j]==0)
						t/=dp[j];
				}
			}
			ans+=vis[t];
			//除去平方因数后的值 ,有多少个该平方因数的值就可以组成多少对 
			vis[t]++;
		}
		printf("%d\n",ans);
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值