线性筛素数:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e7+5;
bool mp[N];
int prime[N];
void getPrime(int n)
{
int cnt = 0;
for(int i = 2; i <= n; i++)
{
if(!prime[i]) prime[++cnt] = i;
for(int j = 1; j <=cnt&&prime[j]<=n/i; j++)
{
prime[i*prime[j]] = 1;
if(i%prime[j] == 0) break;
}
}
for(int i = 1; i <= cnt; i++)
{
mp[prime[i]] = true;
}
}
int main()
{
int n,t;
scanf("%d%d",&n,&t);
getPrime(n);
int x;
while(t--)
{
scanf("%d",&x);
if(mp[x]) puts("Yes");
else puts("No");
}
return 0;
}
米勒卡宾判素数:
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
LL quickPow(LL a,LL b,LL mod)
{
LL res = 1;
a %= mod;
while(b)
{
if(b&1) res = res*a%mod;
b >>= 1;
a = a*a%mod;
}
return res%mod;
}
LL num[] = {2,3,5,7,11,13,17,19};
bool Miller_Rabin(LL x)
{
if(x == 2) return true;
if((x&1)==0||x==1) return false;
for(LL i = 0; i < 8; i++)
if(x == num[i]) return true;
LL tmp = x-1;
LL t = 0,nxt;
while((tmp&1)==0)
{
tmp>>=1;
t++;
}
for(LL i = 0; i < 8; i++)
{
LL a = num[i];
LL now = quickPow(a,tmp,x);
nxt = now;
for(LL j = 1; j <= t; j++)
{
nxt = now * now % x;
if(nxt==1 && now != x-1 && now != 1)
return false;
now = nxt;
}
if(now != 1) return false;
}
return true;
}
int main()
{
LL n,m;
cin>>n>>m;
LL x;
while(m--)
{
cin>>x;
cout<<(Miller_Rabin(x)?"Yes":"No")<<endl;
}
return 0;
}