D. Almost All Divisors
We guessed some integer number x. You are given a list of almost all its divisors. Almost all means that there are all divisors except 1 and x in the list.
Your task is to find the minimum possible integer x that can be the guessed number, or say that the input data is contradictory and it is impossible to find such number.
You have to answer t independent queries.
Input
The first line of the input contains one integer t (1≤t≤25) — the number of queries. Then t queries follow.
The first line of the query contains one integer n (1≤n≤300) — the number of divisors in the list.
The second line of the query contains n integers d1,d2,…,dn (2≤di≤106), where di is the i-th divisor of the guessed number. It is guaranteed that all values di are distinct.
Output
For each query print the answer to it.
If the input data in the query is contradictory and it is impossible to find such number x that the given list of divisors is the list of almost all its divisors, print -1. Otherwise print the minimum possible x.
Example
input
2
8
8 2 12 6 4 24 16 3
1
2
output
48
4
解题思路:
排个序,答案应该是ans = a[0]*a[n-1];
如果存在 a[i] :i∈1~n-2 ,ans%a[i]!=0 输出-1
在求ans的质因子分解,n+2 != Π(pi+1) 输出-1
否则 答案存在 输出ans
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int S=5;
ll factor[333],tot;
ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);}
ll qmul(ll a,ll b,ll c){
ll ans=0;
a%=c,b%=c;
while(b){
if(b&1){
ans+=a;
if(ans>c)ans-=c;
}
a<<=1;;
if(a>c)a-=c;
b>>=1;
}
return ans;
}
ll qpow(ll a,ll b,ll c){
ll ans=1;
a%=c;
while(b){
if(b&1)ans=qmul(ans,a,c);
a=qmul(a,a,c);
b>>=1;
}
return ans;
}
bool check(ll a,ll n,ll x,ll t){
ll ans=qpow(a,x,n);
ll last=ans;
for(int i=1;i<=t;++i){
ans=qmul(ans,ans,n);
if(ans==1&&last!=i&&last!=n-1)return true;
last=ans;
}
return ans!=1;
}
bool Miller_Rabin(ll n){
if(n<2)return false;
if(n==2||n==3||n==5||n==7)return true;
if((n&1)==0)return false;
ll x=n-1,t=0;
srand(time(NULL));
for(int i=0;i<S;++i){
ll a=rand()%(n-1)+1;
if(check(a,n,x,t))return false;
}
return true;
}
ll pollard_rho(ll x,ll c){
srand(time(NULL));
ll i=1,k=2,x0=rand()%(x-1)+1,y=x0;
while(1){
++i;
x0=(qmul(x0,x0,x)+c)%x;
ll d=gcd(abs(y-x0),x);
if(d!=1&&d!=x)return d;
if(y==x0)return x;
if(i==k)y=x0,k<<=1;
}
}
void findfactor(ll n,int k){
if(n==1)return;
if(Miller_Rabin(n)){
factor[tot++]=n;return;
}
ll p=n;
int c=k;
while(p>=n)p=pollard_rho(p,c--);
findfactor(p,k);
findfactor(n/p,k);
}
ll a[333];
map<int,int>mp;
int main(){
ios::sync_with_stdio(0);
int t;cin>>t;
while(t--){
int n;cin>>n;
for(int i=0;i<n;++i)cin>>a[i];
sort(a,a+n);
if(n==1){
if(Miller_Rabin(a[0]))cout<<(a[0]*a[0])<<endl;
else cout<<-1<<endl;
continue;
}
ll ans=a[0]*a[n-1];
int ok=1;
for(int i=1;i<n-1;++i)if(ans%a[i]){
cout<<-1<<endl;
ok=0;
break;
}
if(!ok)continue;
tot=0;mp.clear();
findfactor(ans,107);
ll res=1;
for(int i=0;i<tot;++i)++mp[factor[i]];
for(auto i=mp.begin();i!=mp.end();++i)res*=(i->second+1);
if(res==n+2)cout<<ans<<endl;
else cout<<-1<<endl;
}
return 0;
}