#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <string>
#include <cstring>
#include <ctime>
#define ms(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
/*
Miller_Rabbin 大素数测试
(不能计算long * long)
复杂度: O(logN) * 测试次数
*/
long long pow_mod(long long a, long long x, long long p)
{
long long res = 1;
while (x)
{
if (x & 1)
{
res = res * a % p;
}
x >>= 1;
a = a * a % p;
}
return res;
}
bool test(long long n, long long a, long long d)
{
if (n == 2)
{
return true;
}
if (n == a)
{
return true;
}
if ((n & 1) == 0)
{
return false;
}
while (!(d & 1))
{
d = d >> 1;
}
long long t = pow_mod(a, d, n);
while ((d != n - 1) && (t != 1) && (t != n - 1))
{
t = t * t % n;
d = d << 1;
}
return (t == n - 1 || (d & 1) == 1);
}
// Miller_Rabin() 算法素数判定
// 是素数返回true.( 可能是伪素数, 但概率极小)
// 合数返回false;
/*
速度快, 而且可以判断<2^63 的数
复杂度: O(logN) * 测试次数由于要处理long * long , 所以略慢
*/
const int S = 20; // 随机算法判定次数, S 越大, 判错概率越小
bool Miller_Rabbin(long long n)
{
if (n < 2)
{
return false;
}
if (n == 2)
{
return true;
}
if ((n & 1) == 0)
{
return false; // 偶数
}
for (int i = 0; i < S; i++)
{
long long a = rand() % (n - 1) + 1;
if (!test(n, a, n - 1))
{
return false; //合数
}
}
return true;
}
int main()
{
ll n;
while (cin >> n)
{
if (Miller_Rabbin(n))
{
cout << "True" << endl;
}
else
{
cout << "False" << endl;
}
}
return 0;
}
Miller Rabbin 大素数测试
最新推荐文章于 2024-11-01 17:22:42 发布