1朴素方法(时间复杂度o(sqrt(n))
#include <bits/stdc++.h>
#define maxn 200005
typedef long long ll;
using namespace std;
ll prime(ll n)
{
if(n < 2)return 0;
for(ll i = 2; i * i <= n; i ++)
if(n%i == 0)
return 0;
return 1;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
ll n,m;
cin >> n >> m;
while(m--)
{
ll x;
cin >> x;
if(prime(x))cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}
2 筛除倍数,一个素数的倍数一定不是素数;时间复杂度(o(nloglogn)
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const ll maxn = 10000005;
const ll mod = 1e9 + 7;
bool a[maxn];
ll n,m;
void prime()
{
a[1] = a[0] = 1;
for(int i = 2; i <= n; i ++)
{
if(a[i] == 0)
{
for(int j = 2 * i; j <= n; j += i)
{
a[j] = 1;
}
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin >> n >> m;
prime();
while(m--)
{
ll p;
cin >> p;
if(!a[p])cout << "Yes" << endl;
else cout << "No" << endl;
}
return 0;
}
3一个大于5的素数一定在6的倍数周围(时间复杂度小于sqrt(n))
#include <bits/stdc++.h>
#define maxn 10000005
typedef long long ll;
using namespace std;
ll n,m;
ll prime(ll n)
{
if(n < 2)return 0;
if(n ==2 || n == 3)return 1;
if(n % 6 != 1 && n % 6 != 5)return 0;
for(ll i = 5; i * i <= n; i += 6)
{
if(n % i == 0 || n % (i + 2) == 0)
return 0;
}
return 1;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin >> n >> m;
while(m--)
{
ll x;
cin >> x;
if(prime(x))
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}
4 欧拉筛法 时间复杂度(o(n))
const ll maxn=100000001;
ll prime[maxn]; //就是个素数表
bool sf[maxn]; //判断这个数是不是素数,sf[i]中的i是从1到maxn的数
void sushu()
{ //核心 欧拉筛代码
ll num=0; //num 用来记筛到第几个质数
memset(sf,true,sizeof(sf));
sf[1] = false;
sf[0] = false; //1 0 特判
for(int i = 2;i <= maxn; i ++)
{ //外层枚举1~maxn
if(sf[i]) prime[++num] = i; //如果是质数就加入素数表
for(int j = 1;j <= num;j ++)
{ //内层枚举num以内的质数
if(i * prime[j] > maxn) break; //筛完结束
sf[i * prime[j]] = false; //筛掉...
if(i % prime[j] == 0) break; //避免重复筛
}
}
}