山东省第六届ACM省赛 H---Square Number 【思考】

题目描述

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

题目:每组给你n个数,问这n这数中存在多少对这样的(ai, aj), ai*aj的乘机是一个完全平方数。输出对数。

任何一个整数n都可以这样表示: n=(p^2)*k; p是一个素数或者是1
例如n=1 2 3的时候可以表示成:1=(1^2)*1; 2=(1^2)*2; 3=(1^2)*3;

a1=(p^2)*k1; a2=(q^2)*k2;
if(k1==k2){
  a1*a2的积一定是一个完全平方数
}//原理

code:
#include <stdio.h>
#include  <string.h>

bool prime(int x)
{
    for(int i=2; i*i<=x; i++){
        if(x%i==0) return false;
    }
    return true; //判断素数
}

int a[1000], cnt[1000000+10];

int main()
{
    //将100万以内的"素数的完全平方数"打表
    int e=0;
    for(int i=2; i*i<=1000000; i++){
        if(prime(i))
            a[e++]=i*i;
    }
    int tg; scanf("%d", &tg);
    int n, i, j;
    while(tg--)
    {
        scanf("%d", &n);
        int dd;
        int mm=1;
        memset(cnt,0,sizeof(cnt));
        while(n--){
            scanf("%d", &dd);
            for(i=0; i<e&&a[i]<=dd; i++){
                while(dd%a[i]==0)
                    dd/=a[i];
            }
            if(dd>mm) mm=dd;
            cnt[dd]++;
        }
        long long ans=0;
        for(j=1; j<=mm; j++){
            ans+=(cnt[j]*(cnt[j]-1)/2);
        }
        printf("%lld\n", ans);
    }
}

 


posted @ 2015-08-29 18:15  我喜欢旅行  阅读(330)  评论(0编辑  收藏  举报