山东省第六届ACM省赛 Square Number(数学+思维)

13 篇文章 0 订阅
13 篇文章 0 订阅

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值