Skip to content

Instantly share code, notes, and snippets.

@teh
Created February 21, 2012 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teh/1877044 to your computer and use it in GitHub Desktop.
Save teh/1877044 to your computer and use it in GitHub Desktop.
Miller Rabin primality test
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
@teh
Copy link
Author

teh commented Feb 21, 2012

There are some caveats/corner cases. E.g. n has to be > 3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment