Hineven's Blog

MillerRabin 快速的素数概率判定法

MillerRabin 快速的素数概率判定法

1.作用:快速判断单个数是否为质数

2.原理:

介绍费马小定理:对于每一个素数p,都有ap11(modp)
但是不是对于每一个有ab11(modb)的b都是素数
如果存在b满足上述规则,那么b有1/4的几率为素数

MillerRabin通过多次随机生成b并使用以上方法进行判断,能把错误的几率降到3/4k,其中k为判断次数
分母指数级扩大让概率随k的增大迅速趋近于0。当k达到10时判断错误的几率已经降到百万分之一,k达到20时几乎不会出错。
黑科技的力量啊 = =

typedef long long LL;
namespace millerrabin{
    inline LL advpow(LL a,LL b,LL c){
        LL ret=1;
        while(b){
            if(b&1)ret*=a,ret%=c;
            a*=a;
            a%=c;
            b>>=1;
        }
        return ret;
    }
    int random(const int&mod){
        srand(rand()*rand()*rand());
        return rand()%mod;
    }
    bool jdPrime(const int&num,const int&eps){
        if(num<=3)return true;
        int cnt=0;
        while(cnt<=eps){
            int a=random(num)+2;
            if(num%a==0)continue;
            if(advpow(a,num-1,num)%num!=1)return false;
            cnt++;
        }
        return true;
    }
}
posted @ 2016-08-19 21:29  Hineven  阅读(323)  评论(0编辑  收藏  举报