隐藏
「bsoj1938」素数问题 - Miller-Rabin | Bill Yang's Blog
0%

「bsoj1938」素数问题 - Miller-Rabin

题目大意

    给一个数$n$,要判断$n$是否为素数?


题目分析

复习一下Miller-Rabin。
模板题,学习笔记见这里


代码

without 二次探测

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdlib>
#include<climits>
#include<vector>
#include<cstdio>
#include<cmath>
#include<ctime>
#include<queue>
using namespace std;

typedef long long LL;

inline const LL Get_Int() {
LL num=0,bj=1;
char x=getchar();
while(x<'0'||x>'9') {
if(x=='-')bj=-1;
x=getchar();
}
while(x>='0'&&x<='9') {
num=num*10+x-'0';
x=getchar();
}
return num*bj;
}

LL Quick_Pow(LL a,LL b,LL p) {
LL sum=1;
for(; b; b>>=1,a=a*a%p)if(b&1)sum=sum*a%p;
return sum;
}

const int TIMES=20;

mt19937 g(rand());

bool Miller_Rabin(LL n) {
srand(time(NULL));
for(int i=1; i<=TIMES; i++) {
LL a=g()%(n-1)+1;
if(Quick_Pow(a,n-1,n)!=1)return false;
}
return true;
}

LL n;

int main() {
while(~scanf("%lld",&n))puts(Miller_Rabin(n)?"Yes":"No");
return 0;
}

added 二次探测

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdlib>
#include<climits>
#include<vector>
#include<cstdio>
#include<cmath>
#include<ctime>
#include<queue>
using namespace std;

typedef long long LL;

inline const LL Get_Int() {
LL num=0,bj=1;
char x=getchar();
while(x<'0'||x>'9') {
if(x=='-')bj=-1;
x=getchar();
}
while(x>='0'&&x<='9') {
num=num*10+x-'0';
x=getchar();
}
return num*bj;
}

LL Quick_Pow(LL a,LL b,LL p) {
LL sum=1;
for(; b; b>>=1,a=a*a%p)if(b&1)sum=sum*a%p;
return sum;
}

const int TIMES=10;

mt19937 g(rand());

bool Witness(LL a,LL n) {
LL u=n-1,t=0;
while(u%2==0)t++,u>>=1;
LL x=Quick_Pow(a,u,n);
if(x==1)return false;
for(int i=1; i<=t; i++,x=x*x%n)
if(x!=n-1&&x!=1&&x*x%n==1)return true;
return x!=1;
}

bool Miller_Rabin(LL n) {
if(n==2)return true;
if(n<2||!(n&1))return false;
srand(time(NULL));
for(int i=1; i<=TIMES; i++) {
LL a=g()%(n-1)+1;
if(Witness(g()%(n-1)+1,n))return false;
}
return true;
}

LL n;

int main() {
while(~scanf("%lld",&n))puts(Miller_Rabin(n)?"Yes":"No");
return 0;
}

姥爷们赏瓶冰阔落吧~