題意:
輸入n個因子數,找出一個數x,要求這n個因子都是x的因子數,並且x的因子數必須都在這n個數裏面,若不是,則輸出-1.
思路:
由於x的所有因子數都在這n個數裏面,那麼假設符合條件的話,n個數中的最小數與最大數的乘積就是x,隨後就只用判斷這n個數是否都是x的因子,如果都是的話就判斷n是否等於x的因子總個數,如果等於的話就輸出x,否則,輸出-1.
My Code:
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<algorithm>
#include<queue>
#include<math.h>
#include<set>
using namespace std;
#define INF 1e9
typedef long long ll;
#define PI acos(-1)
int main()
{
int t,n;
ll a[305];
cin >> t;
while(t--)
{
ll ans = 0;
scanf("%d",&n);
for(int i = 0; i < n; i++)
scanf("%lld",&a[i]);
sort(a,a+n);
ans = a[0]*a[n-1];///最小數與最大數的乘積就是x
int cunt = 0;
int flag = 0;
for(int i = 0; i < n; i++)
{
if(ans%a[i] != 0) flag = 1;///如果有不是x的因子,就說明不合法
}
for(ll i = 2; i <= sqrt(ans); i++)///判斷x的因子個數
{
if(ans%i == 0)
{
if(i*i == ans) cunt+=1;
else
{
cunt += 2;
}
}
}
if(cunt == n && flag == 0) printf("%lld\n",ans);///符合條件,輸出x
else printf("-1\n");
}
return 0;
}