给出N个正整数,检测每个数是否为质数。如果是,输出"Yes",否则输出"No"。
(N leq 1000, a_i leq 10^9)
Solution
先筛出 (10^5) 以内的质数,利用这些质数去判断每个给定的数是否为质数,复杂度 (O(N sqrt V/ log V))
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
int prime[MAXN+1]; // Note: Let prime[0] donate the number of primes
// Note: the array "prime" has two different roles in the algorithm
void presolve() {
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]<=MAXN/i;j++) {
prime[prime[j]*i]=1;
if(i%prime[j]==0) break;
}
}
}
signed main() {
presolve();
int n,t;
cin>>n;
while(n--) {
cin>>t;
int flag=0;
int lim=sqrt(t);
for(int i=1;prime[i]<=lim;i++) flag|=(t%prime[i]==0);
cout<<(flag?"No":"Yes")<<endl;
}
}