There is a sequence of n positive integers. Fancycoder is addicted to learn their product, but this product may be extremely huge! However, it is lucky that FancyCoder only needs to find out one factor of this huge product: the smallest factor that contains more than 2 factors(including itself; i.e. 4 has 3 factors so that it is a qualified factor). You need to find it out and print it. As we know, there may be none of such factors; in this occasion, please print -1 instead.
Input
The first line contains one integer T (1≤T≤15), which represents the number of testcases.
For each testcase, there are two lines:
-
The first line contains one integer denoting the value of n (1≤n≤100).
-
The second line contains n integers a1,…,an (1≤a1,…,an≤2×109), which denote these n positive integers.
Output
Print T answers in T lines.
Sample Input
2
3
1 2 3
5
6 6 6 6 6
Sample Output
6
4
要求一个数的所有因子,可以找出这个数的其中一个因子,然后每次让这个数等于这个数除以这个因子,直到不能除了为止,下面是该操作的代码,其中a是要求因子的数,dat中存放该数的除一外的所有因子,但是要注意,最后不能除了之后若该数仍大于1,那么要把这个数放进去,并且这个数自身也要放进去:
dat[dat_i++]=a;
p=a;
for(ll k=2;k<=sqrt(a);++k)
{
while(a%k==0)
{
dat[dat_i++]=k;
a/=k;
}
}
if(a>1&&a!=p)
dat[dat_i++]=a;
这一题中对于每一个数字,它有用的部分其实只有它的所有质因子(包括相等的)。
求出所有数的所有质因子中最小的两个,相乘就是答案。
如果所有数字的质因子个数不到两个,那么就是无解。
解释样例:首先想到一串数的成绩的因子,实际上就是取每一个数的其中一个因子然后相乘的所有情况,例如上面的样例2,6的因子有1.2.3.6,一共有5个6,显然他们最小的因子是取5个1的时候,但是1这个因子不符合题目中的要求所以不能选它,因此我将其中一个1改成次小的2,但是2也不符合题目中的要求,于是我再将一个1换成一个2,这样就是4,符合题目的要求且是最小的。
为什么不能选用1作为两个相乘因子中的一员:很容易就能想到,如果这个数是质数,那么1乘这个数还是质数,不符合题意,如果这个数是合数,那么肯定还存在比这个合数要小的质因子,因此1不能作为其中一个乘数。
为什么所有数的非1因子大于2个一定有解:很容易能想到,非1的两数相乘的因子一定至少有三个。
下面是完整代码:
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long ll;
bool isprime(ll n)
{
for(ll i=2;i<=sqrt(n);++i)
{
if(n%i==0) return false;
}
return true;
}
ll dat[1000005];
int main()
{
ll t,n,a,dat_i,p;
cin>>t;
for(ll i=1;i<=t;++i)
{
dat_i=0;
cin>>n;
for(ll j=1;j<=n;++j)
{
cin>>a;
if(a==1) continue;
dat[dat_i++]=a;
p=a;
for(ll k=2;k<=sqrt(a);++k)
{
while(a%k==0)
{
dat[dat_i++]=k;
a/=k;
}
}
if(a>1&&a!=p)
dat[dat_i++]=a;
}
sort(dat,dat+dat_i);
if(dat_i<2) cout<<-1<<endl;
else cout<<dat[0]*dat[1]<<endl;
}
return 0;
}