题意:求一串数乘积的因子中的最小合数;
思路:比赛时枚举因子,枚举到两个时结束,估计超时,结果果然被叉了;
将每个数分解,取最小的两个质因子,若数目少于2,则不存在;
#include<cstdio> #include<cstring> #include<vector> #include<algorithm> using namespace std; int t,n,m; int num[505]; const int MAXN=100000; int prime[MAXN+1]; void getprime(){ memset(prime,0,sizeof(prime)); for(int i=2;i<=MAXN;i++){ if(!prime[i]) prime[++prime[0]]=i; for(int j=1;j<=prime[0]&&prime[j]*i<=MAXN;j++){ prime[prime[j]*i]=1; if(i%prime[j]==0) break; } } } long long factor[100][2]; int cnt; int getfactor(long long x){ cnt=0; long long tmp=x; for(int i=1;prime[i]<=tmp/prime[i];i++){ factor[cnt][1]=0; if(tmp%prime[i]==0){ factor[cnt][0]=prime[i]; while(tmp%prime[i]==0){ factor[cnt][1]++; tmp/=prime[i]; } cnt++; } } if(tmp!=1){ factor[cnt][0]=tmp; factor[cnt++][1]=1; } return cnt; } int main(){ int i,j,k; getprime(); scanf("%d",&t); while(t--){ scanf("%d",&n); vector<int> ans; for(i=0;i<n;i++){ scanf("%d",&num[i]); getfactor(num[i]); for(j=0;j<cnt;j++){ while(factor[j][1]--){ ans.push_back(factor[j][0]); } } } sort(ans.begin(),ans.end()); if(ans.size()<2){ printf("-1\n"); } else{ printf("%I64d\n",(long long)ans[0]*ans[1]); } } return 0; }
时间: 2024-10-01 04:12:38