Miller-Rabin算法详解
infinite2021 · · 个人记录
首先说一个前置定理
费马小定理
证明:
有性质在
所以有
化简得
由于
得到
证毕。
那么,我们是不是可以说如果存在整数
看起来是很显然的,但是我们能够举出反例
也就是说,利用费马小定理判断质数是错误的,但是我们可以人为去将它的错误率降到很低。
我们接着引入二次探测定理。
二次探测定理
若
证明
即
因式分解得
又由唯一分解定理得
则
我们继续来看 Miller-Rabin 算法的流程
假设我们要判断
我们先把
若
随机选一个
不断地自乘,结合二次探测定理判断。
然后自乘
如果最后计算出的数不为
这个算法的错误率是
其中,
时间复杂度是
然后我们一般用
贴一下代码
#include <bits/stdc++.h>
using namespace std;
#define int __int128
const int N=111;
int t;
int test[]={2,3,5,7,11,13,17};
inline int read() {
char c = getchar(); int x = 0, f = 1;
while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
int qmi(int a,int b,int p)
{
int res=1;
while(b)
{
if(b&1)res=res*a%p;
a=a*a%p;
b>>=1;
}
return res;
}
bool miller(int p)
{
if(p==1)return 0;
int t=p-1,k=0;
while(!(t&1))k++,t>>=1;
for(int i=0;i<4;i++)
{
if(p==test[i])return 1;
int a=qmi(test[i],t,p),ne=a;
for(int j=1;j<=k;j++)
{
ne=(a*a)%p;
if(ne==1&&a!=1&&a!=p-1)return 0;
a=ne;
}
if(a!=1)return 0;
}
return 1;
}
signed main()
{
t=read();
while(t--)
{
if(miller(read()))cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}