Last active
August 29, 2015 14:14
-
-
Save ssanin82/8e3c2ff2ae6fde1c9a7b to your computer and use it in GitHub Desktop.
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_prime(n, k=5): | |
if n < 6: | |
return [False, False, True, True, False, True][n] | |
elif n & 1 == 0: | |
return False | |
else: | |
s, d = 0, n - 1 | |
while d & 1 == 0: | |
s, d = s + 1, d >> 1 | |
for a in random.sample(xrange(2, min(n - 2, sys.maxint)), min(n - 4, k)): | |
x = pow(a, d, n) | |
if x != 1 and x + 1 != n: | |
for r in xrange(1, s): | |
x = pow(x, 2, n) | |
if x == 1: | |
return False | |
elif x == n - 1: | |
a = 0 | |
break | |
if a: | |
return False | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment