普通素数判断
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main(){
int n;
cin >> n;
if(n == 2){
cout << "Yes" << endl;
return 0;
}
if(n%2 == 0||n <= 1){
cout << "NO" << endl;
return 0;
}
int m = sqrt(n);
int flag = 0;
for(int i = 3;i <= m;i += 2){
if(n%i == 0){
flag = 1;
break;
}
}
if(flag) cout << "No" << endl;
else cout << "Yes" << endl;
return 0;
}
埃氏筛
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 10000010;
int p[maxn];
int a[maxn] = {0};
void prime(){
a[0] = 1;
a[1] = 1;
int m = sqrt(maxn);
for(int i = 2;i <= m;i++){
if(!a[i]){
for(int j = i*i;j <= maxn;j += i){
a[j] = 1;
}
}
}
}
int main(){
prime();
int tt;
cin >> tt;
while(tt--){
int n;
cin >> n;
if(a[n]) cout << "No" << endl;
else cout << "Yes" << endl;
}
return 0;
}
欧拉筛(线性筛)
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 10000010;
int p[maxn];
int a[maxn] = {0};
int t = 0;
void prime(){
a[0] = 1;
a[1] = 1;
for(int i = 2;i <= maxn;i++){
if(!a[i]) p[t++] = i;
for(int j = 0;j<t&&i*p[j] <= maxn;j++){
a[i*p[j]] = 1;
if(i%p[j] == 0) break;
}
}
}
int main(){
prime();
int tt;
cin >> tt;
while(tt--){
int n;
cin >> n;
if(a[n]) cout << "No" << endl;
else cout << "Yes" << endl;
}
return 0;
}