下面判断梅森素数的代码只能判断2的低次幂是否是梅森素数,要想判断2的高次幂,比如2的965次方减一是不是梅森素数该怎么办呢?
#include
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef long long LL;
const int Times=10;
LL multi(LL a,LL b,LL m)
{
LL ans=0;
while(b)
{
if(b&1)
{
ans=(ans+a)%m;
b--;
}
b>>=1;
a=(a+a)%m;
}
return ans;
}
LL quick_mod(LL a,LL b,LL m)
{
LL ans=1;
a%=m;
while(b)
{
if(b&1)
{
ans=multi(ans,a,m);
b--;
}
b>>=1;
a=multi(a,a,m);
}
return ans;
}
bool Miller_Rabin(LL n)
{
if(n==2) return true;
if(n<2||!(n&1)) return false;
LL a,m=n-1,x,y;
int k=0;
while((m&1)==0)
{
k++;
m>>=1;
}
for(int i=0;i<Times;i++)
{
a=rand()%(n-1)+1;
x=quick_mod(a,m,n);
for(int j=0;j<k;j++)
{
y=multi(x,x,n);
if(y==1&&x!=1&&x!=n-1) return false;
x=y;
}
if(y!=1) return false;
}
return true;
}
int main()
{
LL n,t;
cin>>t;
while(t--)
{
cin>>n;
n=((LL)1<<n)-1;
if(Miller_Rabin(n)) puts("yes");
else puts("no");
}
return 0;
}
2的965次方值太大了,long long根本就不够用。改成double吧,勉强够。再大的话,double型也不够了