-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathprimality.py
51 lines (46 loc) · 1.25 KB
/
primality.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
import random
class Primality_test():
def __init__(self):
pass
def doFermatPrimalityTest(self, n: int, round: int = 200) -> bool:
for _ in range(round):
a = random.randint(2, n - 1)
if pow(a, n - 1, n) == 1:
pass
else:
return False
return True
def doMillerRabinPrimalityTest(self, n: int, round: int = 100) -> bool:
for _ in range(round):
a = random.randint(2, n - 2)
d = n - 1
r = 0
while pow(d, 1, 2) == 1:
r += 1
x = pow(a, r, n)
if x == 1 or x == n - 1:
pass
else:
for _ in range(r - 1):
x = pow(x, 2, n)
if x == n - 1:
break
else:
pass
return False # composite
return True
def isPrime(self, randomNumber: int) -> bool:
if randomNumber <= 1:
return False
elif randomNumber % 2 == 0:
return False
else:
# Fermat's primality test
if self.doFermatPrimalityTest(randomNumber, 10): # probably true
# Miller-Rabin primality test
if self.doMillerRabinPrimalityTest(randomNumber, 100): # probably true
return True
else: # composite found
return False
else: # witness found
return False