First commit
This commit is contained in:
commit
43a72c3fb7
12 changed files with 213 additions and 0 deletions
40
lib/miller_rabin.py
Normal file
40
lib/miller_rabin.py
Normal file
|
@ -0,0 +1,40 @@
|
|||
# Python Miller-Rabin implementation
|
||||
|
||||
import random
|
||||
import lib.arithmetics as arithm
|
||||
|
||||
def get_d_and_s(n: int) -> (int, int):
|
||||
d = n - 1
|
||||
s = 0
|
||||
while d % 2 == 0:
|
||||
d //= 2
|
||||
s += 1
|
||||
return (d, s)
|
||||
|
||||
def rabin_witness(n: int, a: int) -> bool:
|
||||
d, s = get_d_and_s(n)
|
||||
x = arithm.modpow(a, d, n)
|
||||
if x == 1 or x == n - 1:
|
||||
return False
|
||||
for _ in range(s - 1):
|
||||
x = arithm.modpow(x, 2, n)
|
||||
if x == n - 1:
|
||||
return False
|
||||
return True
|
||||
|
||||
def miller_rabin(n: int, k: int) -> bool:
|
||||
if n < 3: return False
|
||||
for _ in range(k):
|
||||
a = random.randint(2, n - 1)
|
||||
if rabin_witness(n, a): return False
|
||||
return True
|
||||
|
||||
def is_prime(n: int) -> bool:
|
||||
return miller_rabin(n, 25)
|
||||
|
||||
def get_random_prime(n: int) -> int:
|
||||
a = random.randint(2**(n-1), 2**(n) - 1)
|
||||
while not is_prime(a):
|
||||
a = random.randint(2**(n-1), 2**(n) - 1)
|
||||
return a
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue