-
Notifications
You must be signed in to change notification settings - Fork 0
/
Miller-Rabin.py
76 lines (69 loc) · 1.87 KB
/
Miller-Rabin.py
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
67
68
69
70
71
72
73
74
75
76
from toolkit import *
def Miller_Rabin_test(n: int) -> bool:
# sieve out the even number
if not (n & 1):
return False
s, t = 0, n - 1
while not t & 1: # stop when end is odd
t = divmod(t, 2)[0]
s += 1
# print(s, t)
k = 30
while k:
b = 2
while gcd(b, n) != 1:
b = randint(1)
# generates b that (b, n) = 1
b = pow(b, t, n)
if abs(b) == 1:
return True
s -= 1
canpass = False
while s > 0:
# print(k)
b = pow(b, 2, n)
if b == n - 1:
canpass = True
break
s -= 1
if not canpass:
return False
k -= 1
return True
def Miller_Rabin_test_by_b(n: int, b: int) -> bool:
if not (n & 1):
return False
# sieve out the even number
s, t = 0, n - 1
while not t & 1: # stop when end is odd
t = divmod(t, 2)[0]
s += 1
# print(s, t)
b = pow(b, t, n)
if abs(b) == 1:
return True
s -= 1
while s > 0:
b = pow(b, 2, n)
if b == n - 1:
return True
s -= 1
return False
if __name__ == '__main__':
n = randint(4)
while len(str(n)) < 10:
n = randint(4)
found = Miller_Rabin_test(n)
while not found:
n = randint(4)
while len(str(n)) < 10:
n = randint(4)
found = Miller_Rabin_test(n)
print('Prime number generated by Miller-Rabin test is', n)
nlst = [17 * 19, 23 * 47]
for n in nlst:
blst = [i for i in range(n)]
# print(blst)
for b in blst:
if Miller_Rabin_test_by_b(n, b):
print(n, 'is a STRONG pseudoprime of base', b)