山东省第六届ACM大学生程序设计竞赛-Square Number(完全平方数)

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

提示

 

来源

 

示例程序


题目意思:

有一些数据,两个为一组,两两相乘为完全平方数的有多少组?


解题思路:

一个完全平方数可以分解成偶数个素数相乘。

由↑这个思路,我们可以先打一个素数表,然后遍历素数表。

设一个数m为使得m与这个数相乘是一个完全平方数的数,算出这个数能被素数prm[j]整除的次数,如果是奇数次就乘到m上;把遍历最后剩下的数也乘到m上去。


这个素数表很重要哇,选不好效率高的素数表就要TLE啦~

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
#define MAXN 1000010
int a[MAXN],vis[MAXN];
long long ans;
bool is[MAXN];//用来求素数
int prm[MAXN];//用来保存素数
int totleprm=0;//记录素数总个数

void getprm()//打素数表
{
    int i,j,m;
    memset(is,0,sizeof(is));
    is[1]=1;
    m=sqrt(MAXN);
    for(i=2; i<=m; i++)
        if(!is[i])
            for(j=i*i; j<MAXN; j+=i)
                is[j] = 1;
    for(i=2; i<MAXN; i++)
        if(!is[i])
            prm[totleprm++]=i;
}

int main()
{
    int t;
    getprm();//素数打表
    cin>>t;
    while(t--)
    {
        memset(vis,0,sizeof(vis));
        int n,i,j;
        ans=0;
        cin>>n;
        for(i=0; i<n; i++)
        {
            cin>>a[i];//输入数据
            int m=1;//保存应当再乘的数
            for(j=0; j<totleprm; j++)//遍历素数表
            {
                int acnt=0;//保存数a[i]能被素数prm[j]整除的次数
                while(a[i]%prm[j] == 0)
                {
                    a[i]/= prm[j];
                    ++acnt;
                }
                if(acnt%2) m*=prm[j];//如果整除的次数为奇数,就把这个素数乘上
                if(!is[a[i]]||a[i]==1)//a[i]==1这句不加会超时……
                {
                    m*=a[i];//如果除到最后是个素数,把剩的这个数也乘上
                    break;
                }
            }
            ans+=vis[m];
            ++vis[m];//记录应当再乘的数的出现次数,观察在其整个数据序列中出现的次数
        }
        cout<<ans<<endl;
    }
    return 0;
}
/*
1
5
1 2 3 4 12
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值