Skip to content

Commit 7346944

Browse files
authored
Create miller_robin.cpp
miller robin 素性测试
1 parent b2d9679 commit 7346944

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

template/miller_robin.cpp

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
namespace Prime{
2+
#define random(a,b) (rand() % ((b) -(a)) +(a))
3+
LL power_mod(LL x,LL n,LL mod){
4+
LL ret =1;
5+
while(n){
6+
if(n & 1) ret = x * ret % mod;
7+
x = x * x % mod;
8+
n >>=1;
9+
}
10+
return ret;
11+
}
12+
LL mulmod(LL x,LL y,LL n){ // x ,y <= 10^9
13+
return x * y % n;
14+
}
15+
bool witness(LL a,LL n,LL u,LL t){
16+
LL x0 = power_mod(a,u,n),x1;
17+
for(int i=1 ;i<=t ; ++i){
18+
x1 = mulmod(x0,x0,n);
19+
if(x1==1 && x0!=1 && x0!=n-1)
20+
return false;
21+
x0 = x1;
22+
}
23+
if(x1 !=1)return false;
24+
return true;
25+
}
26+
27+
bool miller_rabin(LL n, int times = 20){
28+
if(n < 3) return n==2;
29+
if(!(n&1))return false;
30+
LL u = n-1,t =0;
31+
while (u%2==0) {
32+
t++;u>>=1;
33+
}
34+
while (times--) {
35+
LL a = random(1,n-1);
36+
//if(a == 0)std::cout << a << " "<<n<< " "<<u<<" " << t<<'\n';
37+
if(!witness(a,n,u,t))return false;
38+
}
39+
return true;
40+
}
41+
};

0 commit comments

Comments
 (0)