质数判定(miller-rabin)

本文详细介绍了使用Miller-Rabin素性测试算法进行高效的大整数素性判断的方法。该算法通过一系列数学运算来验证一个数是否为素数,并且特别适用于大整数的情况。文章还提供了完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<cstdio>
#include<cstring>
#include<cctype>
#include<stdlib.h>
#include<algorithm>
#define LL long long
using namespace std;
 
LL mul(LL a,LL b,LL c){ return ((a*b-(LL)((long double)a/c*b+1e-8)*c)%c+c)%c; }
LL Pow(LL a,LL b,LL c,LL ret=1){for(;b;b>>=1,a=mul(a,a,c))if(b&1)ret=mul(ret,a,c);return ret;}
const int base[6]={2,3,7,31,61,24251};
inline bool Miller_Rabin(LL x)
{
    if(x < 2) return 0;
    for(int i=0;i<6;i++) if(base[i]==x) return 1;
    if(!(x&1)||!(x%3)||!(x%61)||!(x%24251))return false;
    LL res=x-1,k=0,now,pre,tim;
    for(;!(res&1);k++,res>>=1);
    for(int i=0;i<6 && base[i] < x;i++)
    {
        pre = Pow(base[i],res,x);
        for(tim=k;tim && pre!=1;tim--,pre=now)
            if((now=mul(pre,pre,x))==1 && pre!=1 && pre!=x-1) return 0;
        if(pre!=1) return 0;
    }
    return 1;
}
int main()
{
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值