nefu 120 梅森素数

题目:http://acm.nefu.edu.cn/test/problemshow.php?problem_id=120

思路:大数测试

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
#define Times 10
long long random(long long n)
{
    return ((double)rand()/RAND_MAX*n+0.5);
}
long long multi(long long a,long long b,long long m)
{
    long long ans=0;
    while(b)
    {
        if(b&1)
        {
            b--;
            ans=(ans+a)%m;
        }
        else
        {
            b/=2;
            a=(2*a)%m;
        }
    }
    return ans;
}
long long Pow(long long a,long long b,long long m)
{
    long long ans=1;
    while(b)
    {
        if(b&1)
        {
            b--;
            ans=multi(ans,a,m);
        }
        else
        {
            b/=2;
            a=multi(a,a,m);
        }
    }
    return ans;
}
bool witness(long long a,long long n)
{
    long long d=n-1;
    while(!(d&1))
        d>>=1;
    long long t=Pow(a,d,n);
    while(d!=n-1 && t!=1 && t!=n-1)
    {
        t=multi(t,t,n);
        d<<=1;
    }
    return t==n-1 || d&1 ;
}
bool miller_rabin(long long n)
{
    if(n==2)
        return true;
    if(n<2||!(n&1))
        return false;
    for(int i=1;i<=Times;i++)
    {
        long long a=random(n-2)+1;
        if(!witness(a,n))
            return false;
    }
    return true;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        long long n;
        cin>>n;
        long long ans=1;
        ans<<=n;
        ans--;
        if(miller_rabin(ans))
            cout<<"yes"<<endl;
        else
            cout<<"no"<<endl;
    }
    return 0;
}
View Code

 

posted @ 2013-07-12 21:02  over_flow  阅读(162)  评论(0编辑  收藏  举报