在好久之后终于搞完了miller-rabbin素性测试,谈谈自己的理解
要判断的数设为 a,
主要思想就是运用费马小定理来搞,随机几个数x(x<=a-1),判断x^(a-1)=1(mod a)是否成立,如果有不成立,a肯定不是素数
这是有一定错误几率的,随机n个数的错误几率为4^(-n)
这么看来,肯定是多来几组随机数比较保险,10比较稳
期间加入了二次探测定理,以提高miller-rabbin的效率
二次探测定理:若p是奇素数 x^2=1 (mod p) x的解一定为 1或p-1
如果不满足此定理,一样是合数
code
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<cmath>
#include<vector>
#include<cstdlib>
#include<iostream>
#include<ctime>
#define ll long long
#define inf 2147483647
#define N 10
using namespace std; ll quick_mul(ll a, ll b, ll n) {
ll res = ;
while(b) {
if(b&) res = (res + a) % n;
a = (a + a) % n;
b >>= ;
}
return res;
} ll quick_pow(ll a, ll b, ll n) {
ll res = ;
while(b) {
if(b&) res = quick_mul(res, a, n);
a = quick_mul(a, a, n);
b >>= ;
}
return res;
}
bool miller_rabin(ll x){
if(x==||x==||x==||x==||x==)return ;
if(x==||!(x%)||!(x%)||!(x%)||!(x%)||!(x%))return ;
ll n=x-;int k=;
while(!(n&)){n>>=;k++;}//这么做是为了顺便加上二次探测定理 srand((ll)time());
for(int i=;i<=N;i++){
ll t=rand()%(x-)+,pre;
if(!t)continue;
t=quick_pow(t,n,x);
pre=t;
for(int i=;i<=k;i++){
t=quick_mul(t,t,x);
if(t==&&pre!=&&pre!=x-)return ;
pre=t;
}
if(t!=)return ;
}
return ; } int main(){
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
int l,r,cnt=;
scanf("%d%d",&l,&r);
for(int i=l;i<=r;i++){
if(miller_rabin(i))cnt++;
}
printf("%d",cnt);
return ;
}