素数相关模板

线性筛素数:

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Leo Bliss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值