I'm trying to implement the Miller-Rabin algorithm on Python.
I have coded just as my textbook's pseudocode says, but for some reason, it it not working as I have expected.
To be sepcific, the function 'test' returns sometimes return 'true' when it goes to Fermat test.
def miller_rabin(n, s):
if n == 2:
return Prime
elif n % 2 == 0:
return Composite
for _ in range(s):
a = random.randint(1, n-1)
if test(a, n) == True:
return Composite
return Prime
def test(a, n):
t, u = 0, n-1
while (u % 2 == 0):
t += 1 #t >= 1, u is odd, n=1 = 2^t * u
u //= 2 #initialization
x = exp(a, u, n) #initializing x0 = a^u mod n
for _ in range(t-1): #for i = 1 to t
x_prev = x #xi-1
x = exp(x_prev, 2, n) #xi = (xi-1)^2 mod n
if x == 1 and x_prev != 1 and x_prev != (n-1): #NSR test
return True
if x != 1: #Fermat test
return True
return False
I have been struggling because of this for few hours, and still cannot find which part of the code is the problem. Please let me know if you have any advice. P.S. exp (a,b,c) returns a^b mod c.