51nod-1186 质数检测 V2

44 篇文章 0 订阅

地址:http://www.51nod.com/Challenge/Problem.html#!#problemId=1186

思路:Miller-Rabin随机算法+__int128大法

Code:

#include<iostream>
using namespace std;
typedef long long LL;
typedef __int128 LLL;

LLL mod_mul(LLL a, LLL b, LLL mod)
{
    LLL res = 0;
    while (b)
    {
        if (b & 1)
            res = (res + a) % mod;
        a = (a + a) % mod;
        b >>= 1;
    }
    return res;
}
 
LLL mod_pow(LLL a, LLL n, LLL mod)
{
    LLL res = 1;
    while (n)
    {
        if (n & 1)
            res = mod_mul(res, a, mod);
        a = mod_mul(a, a, mod);
        n >>= 1;
    }
    return res;
}
 
// Miller-Rabin随机算法检测n是否为素数
bool Miller_Rabin(LLL n)
{
    if (n == 2)
        return true;
    if (n < 2 || !(n & 1))
        return false;
    LLL m = n - 1, k = 0;
    while (!(m & 1))
    {
        k++;
        m >>= 1;
    }
    for (int i = 1; i <= 20; i++)  // 20为Miller-Rabin测试的迭代次数
    {
        LLL a = rand() % (n - 1) + 1;
        LLL x = mod_pow(a, m, n);
        LLL y;
        for (int j = 1; j <= k; j++)
        {
            y = mod_mul(x, x, n);
            if (y == 1 && x != 1 && x != n - 1)
                return false;
            x = y;
        }
        if (y != 1)
            return false;
    }
    return true;
}

int main()
{
	LLL n;
	string str;
	while(cin>>str){
		n=0;
		int len=str.length();
		for(int i=0;i<len;++i)
			n=n*10+str[i]-'0';
		cout<<(Miller_Rabin(n)?"YES":"NO")<<endl;
	}
	
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值