Lucas-Lehmer判定法
//判斷一個數是不是梅森素數
#include <iostream>
using namespace std;
typedef long long LL;
LL sum, data[66], tmp;
LL multi(LL a, LL b, LL m)//a*b%m
{
LL ret=0;
while (b)
{
if (b&1) ret=(ret+a)%m;
b>>=1;
a=(a<<1)%m;
}
return ret;
}
bool is_meisen_prime(int p)//判斷2^p-1是不是梅森素數
{
if (p==2) return 1;
sum=(1<<p)-1;
for (int i=2; i<=p-1; i++)
{
tmp=multi(data[i-1], data[i-1], sum);
data[i]=(tmp-2)%sum;
}
if (data[p-1]==0) return 1;
else return 0;
}
Miller素數測試方法
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;
#define N 5//修改產生隨機數的個數,越多越準確
typedef long long LL;
LL random(LL n)
{
return (LL)((double)rand()/RAND_MAX*n+0.5);
}
LL multi(LL a, LL b, LL m)// a*b%m
{
LL ret=0;
while (b)
{
if (b&1) ret=(ret+a)%m;
b>>=1;
a=(a<<1)%m;
}
return ret;
}
LL quick_mod(LL a, LL b, LL m)//(a^b)%m
{
LL ans=1;
while (b)
{
if (b&1) ans=multi(ans, a, m);
b>>=1;
a=multi(a, a, m);
}
return ans;
}
bool miller_rabin(LL n)//判斷是不是素數
{
for (int i=1; i<=N; i++)
{
LL a=random(n-2)+1;
if (quick_mod(a, n-1, n)!=1)//是否符合費馬小定理,不符合直接return false
return false;
}
return true;
}
bool is_meisen_prime(int p)//判斷2^p-1是不是梅森素數
{
LL sum=(1<<p)-1;
if (miller_rabin(sum)) return 1;
else return 0;
}