I used some code taken from Rosetta Code. I renamed a few things but I didn't really change anything.
import random
def is_probable_prime(n, num_trials = 5):
assert n >= 2
if n == 2:
return True
if n % 2 == 0:
return False
s = 0
d = n-1
while True:
quotient, remainder = divmod(d, 2)
if remainder == 1:
break
s += 1
d = quotient
assert(2**s * d == n-1)
def try_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True
for i in range(num_trials):
a = random.randrange(2, n)
if try_composite(a):
return False
return True
It pretty closely matches some psuedocode. However, when I test the number
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901
it returns False
. Other (python and java) implementations of Miller-Rabin return True
for probable prime. After some testing, try_composite
returns True
after only 2
rounds! I would really like to know any error, I'm guessing a mis-indent or some feature I don't know about.