036.Miller-Rabin 素性测试

判断较大素数

模板检测

复杂度O(k(logn)^3)

kp[] 的数量

#include<bits/stdc++.h>
using namespace std;
typedef __int128 LL;
template<typename T>void read(T&x){
    x=0;bool f=0;
    char ch=getchar();
    while(ch<'0'||ch>'9'){
        if(ch=='-')f=1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9'){
        x=(x<<3)+(x<<1)+(ch^48);
        ch=getchar();
    }
    if(f)x=-x;
}
LL p[]={2,3,5,7,11,13,17,19,23,29,31,37,41,43};
LL mul(LL a,LL b,LL mod){
    LL res=0;
    a%=mod;
    while(b){
        if(b&1)res=(res+a)%mod;
        a=(a<<1)%mod;
        b>>=1;
    }
    return res;
}
LL qpow(LL b,LL e,LL mod){
    LL ans=1;
    b%=mod;
    while(e){
        if(e&1)ans=mul(ans,b,mod);
        b=mul(b,b,mod);
        e>>=1;
    }
    return ans;
}
bool miller_rabin(LL n){
    if(n<3||n%2==0)return n==2;
    LL u=n-1,t=0;
    while(u%2==0)u/=2,++t;
    for(auto a:p){
        if(n==a)return 1;
        if(n%a==0)return 0;
        LL v=qpow(a,u,n);
        if(v==1)continue;
        LL s=1;
        for(;s<=t;++s){
            if(v==n-1)break;
            v=mul(v,v,n);
        }
        if(s>t)return 0;
    }
    return 1;
}
posted @ 2026-01-06 22:38  射杀百头  阅读(7)  评论(0)    收藏  举报