Created
February 21, 2012 15:33
-
-
Save teh/1877044 to your computer and use it in GitHub Desktop.
Miller Rabin primality test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
def is_probably_prime(n, num_iterations): | |
s = bin(n - 1)[::-1].index('1') | |
d = n // 2**s | |
for k in range(num_iterations): | |
a = random.randint(2, n - 2) | |
x = pow(a, d, n) | |
if x == 1 or x == n - 1: | |
continue | |
for r in xrange(1, s): | |
x = pow(x, 2, n) | |
if x == 1: | |
return False | |
if x == n - 1: | |
break | |
else: | |
return False | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There are some caveats/corner cases. E.g. n has to be > 3.