C++実装Miller-Rabin素性試験プログラム
2096 ワード
Miller‐Rabin素性試験アルゴリズムは確率アルゴリズムであり,決定アルゴリズムではない.しかし,試験の計算速度は速く,比較的有効であり,広く用いられている.
もう一つの紹介に値するアルゴリズムはAKSアルゴリズムで、3人のインド人が発明したもので、AKSは彼らの姓の頭文字です.ASKアルゴリズムは決定アルゴリズムであり,その時間的複雑さは多項式に相当し,計算可能なアルゴリズムに属する.
コードはSanfoundryのC++Program to Implement Miller Rabin Primality Testから来ています.
ソースプログラムは次のとおりです.
転載先:https://www.cnblogs.com/tigerisland/p/7564853.html
もう一つの紹介に値するアルゴリズムはAKSアルゴリズムで、3人のインド人が発明したもので、AKSは彼らの姓の頭文字です.ASKアルゴリズムは決定アルゴリズムであり,その時間的複雑さは多項式に相当し,計算可能なアルゴリズムに属する.
コードはSanfoundryのC++Program to Implement Miller Rabin Primality Testから来ています.
ソースプログラムは次のとおりです.
/*
* C++ Program to Implement Miller Rabin Primality Test
*/
#include
#include
#include
#define ll long long
using namespace std;
/*
* calculates (a * b) % c taking into account that a * b might overflow
*/
ll mulmod(ll a, ll b, ll mod)
{
ll x = 0,y = a % mod;
while (b > 0)
{
if (b % 2 == 1)
{
x = (x + y) % mod;
}
y = (y * 2) % mod;
b /= 2;
}
return x % mod;
}
/*
* modular exponentiation
*/
ll modulo(ll base, ll exponent, ll mod)
{
ll x = 1;
ll y = base;
while (exponent > 0)
{
if (exponent % 2 == 1)
x = (x * y) % mod;
y = (y * y) % mod;
exponent = exponent / 2;
}
return x % mod;
}
/*
* Miller-Rabin primality test, iteration signifies the accuracy
*/
bool Miller(ll p,int iteration)
{
if (p < 2)
{
return false;
}
if (p != 2 && p % 2==0)
{
return false;
}
ll s = p - 1;
while (s % 2 == 0)
{
s /= 2;
}
for (int i = 0; i < iteration; i++)
{
ll a = rand() % (p - 1) + 1, temp = s;
ll mod = modulo(a, temp, p);
while (temp != p - 1 && mod != 1 && mod != p - 1)
{
mod = mulmod(mod, mod, p);
temp *= 2;
}
if (mod != p - 1 && temp % 2 == 0)
{
return false;
}
}
return true;
}
//Main
int main()
{
int iteration = 5;
ll num;
cout<>num;
if (Miller(num, iteration))
cout<
転載先:https://www.cnblogs.com/tigerisland/p/7564853.html