Miller Rabin 素性测试 学习笔记

Miller_Rabin素性测试:

二次探测定理:

\(p\)是质数,且\(x^2\equiv 1 \pmod p\)
则:

\(x\equiv1\pmod p\)\(x\equiv p-1\pmod p\),且他的逆定理成立。

证明:

\[\because x^2\equiv 1\pmod p\]

\[\therefore (x+1)(x-1)\equiv 0\pmod p\]

\[\therefore p|(x+1)\]\[ p|(x-1)\]

\(\therefore\)得证。

至于逆定理为啥成立我也不知道

欧拉函数:

\(\phi (x)\)表示\(<x\)的数中与\(x\)互质的数的个数。

显然,一个合数的\(\phi\)值很小。

Miller_Rabin算法:

假设我现在要测\(n\)是否是素数,钦定\(n>2\)

随机几个素数\(a\),对于每一个\(a\),计算:

\[a^{n-1}\bmod n\]

因为\(n\)是奇数,
所以\(n-1\)是偶数.

\[a^{n-1}\bmod n\]

分解成\[a^{2^k*t}\bmod n\]

计算时,先算\(a^t\),然后不停平方,每次用二次探测定理判断他是否是素数。最后算到\(a^{n-1}\),用费马小定理判断是否是素数。如果

\[a^{n-1}\bmod n!\equiv 1\]

那么n一定是合数。

如果\(a^{2^i*t}\equiv 1\pmod n\)符合二次探测定理

而且\(a^{2^{i-1}*t}!\equiv 1\pmod n\)

并且\(a^{2^{i-1}*t}!\equiv n-1\pmod n\)

那么n就是合数。

以上都没判断出来的,就有\(\frac{3}{4}\)的几率是质数了。

证明:

据说可以用欧拉函数证,但我不会证qwq

Code

bool check(int p,ll n)
{
    if(p==n)
        return 1;
    if(quick_pow(p,n-1,n)!=1)
        return 0;
    ll s=0,k=n-1;
    while(!(k&1))
    {
        k>>=1;
        s++;
    }
    ll last=quick_pow(p,k,n);
    for(int i=1;i<=s;i++)
    {
        ll now=last*last%n;
        if(now==1)
            return last==n-1||last==1;
        last=now;
    }
    return 0;
}
等等,还有一件事!

\(N<4,759,123,141\),选取 \(a=2,7,61\) 即可确保算法得出正确结果。

\(N<3,825,123,056,546,413,051≈3*10^{18}\),选取\(a=2,3,5,7,11,13,17,19,23\)即可确保算法得出正确结果。

\(N<18,446,744,073,709,551,616=2^{64}\),选取 \(a=2,3,5,7,11,13,17,19,23,29,31,37\)即可确保算法得出正确结果。

猜你喜欢

转载自www.cnblogs.com/oierwyh/p/11375111.html
今日推荐