Miller Rabin 总结

费马小定理

\(a^{p-1}\equiv 1\pmod p\)
在 p 是质数时成立,考虑 rand 一个 a 来判定
但是有一类数,满足费马小定理却又不是质数,如 561

二次探测定理

方程 \(x^2\equiv 1\pmod p\) 的解是 \(x=1,p-1\) ,如果不是,则 \(p\) 不是质数

移项、平方差 \((x+1)(x-1)\equiv0\pmod p\) ,当 \(p\) 是素数时, \(x=1,p-1\)

\(p-1\) 分解为 \(2^r*k\) ,则 \(a^{p-1}=(a^k)^{2^r}\)

可以得到 \(a^k\) ,然后不断平方,利用二次探测定理探测

\(a\) 取常见的几个素数即可在 long long 内几乎无错

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef unsigned long long uLL;
typedef long double LD;
inline LL Abs(LL x) { return x<0?-x:x; }
inline LL Mul(uLL x,uLL y,LL p) { return (x*y-(uLL)((LD)x/p*y)*p+p)%p; }
inline LL Pow(LL x,LL y,LL p){
	register LL res=1;
	for(;y;y>>=1,x=Mul(x,x,p))
	if(y&1)res=Mul(res,x,p);
	return res;
}
inline bool Mr(LL n,LL p) {
    if(Pow(p,n-1,n)!=1)return 0;
    register LL q=n-1,o;
    while(!(q&1)) {
        q>>=1,o=Pow(p,q,n);
        if(o!=1 && o!=n-1)return 0;
        if(o==n-1)return 1;
    }
    return 1;
}
inline bool Prime(LL n) {
    if(n<2)return false;
    if(n==2||n==3||n==5||n==7||n==43)return true;
    return Mr(n,2)&&Mr(n,3)&&Mr(n,5)&&Mr(n,7)&&Mr(n,43);
}
int main() {
    srand(20080816);
    return 0;
}
posted @ 2021-01-26 19:28  小蒟蒻laf  阅读(77)  评论(0编辑  收藏  举报