-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMiller-Rabin primality test.cpp
More file actions
60 lines (57 loc) · 1.08 KB
/
Miller-Rabin primality test.cpp
File metadata and controls
60 lines (57 loc) · 1.08 KB
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
typedef unsigned long long int int64;
int64 Multiply(int64 a, int64 b, int64 mod) {
int64 res(0);
while (b) {
if (b & 1) {
res += a;
if (res >= mod)
res -= mod;
}
a <<= 1;
if (a >= mod)
a -= mod;
b >>= 1;
}
return res;
}
int64 Powlog(int64 a, int64 b, int64 mod) {
int64 res(1);
while (b) {
if (b & 1)
res = Multiply(res, a, mod);
a = Multiply(a, a, mod);
b >>= 1;
}
return res;
}
bool is_prime(int64 n) {
if (n < 2)
return false;
if (n == 2 || n == 3 || n == 5)
return true;
if (n % 2 == 0 || n % 3 == 0 || n % 5 == 0)
return false;
int64 d(n - 1);
while (d % 2 == 0)
d >>= 1;
for (int i = 1; i <= 2; ++i) {
bool ch(true);
int64 a = 2 + rand() % (n - 4), temp(d);
int64 x = Powlog(a, temp, n);
if (x == 1 || x == n - 1)
continue;
while (temp != n - 1) {
x = Multiply(x, x, n);
temp <<= 1;
if (x == 1)
return false;
if (x == n - 1) {
ch = false;
break;
}
}
if (ch)
return false;
}
return true;
}