51nod-1186 质数检测 V2

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/C_13579/article/details/83830836

地址: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;
}

猜你喜欢

转载自blog.csdn.net/C_13579/article/details/83830836