Last active
January 4, 2019 08:35
-
-
Save igorvolnyi/3c2609997774407263fc8c13be7de64a to your computer and use it in GitHub Desktop.
Test if a number is prime in python
This file contains 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
# Taken from | |
# @see https://www.daniweb.com/programming/software-development/code/216880/check-if-a-number-is-a-prime-number-python | |
def is_prime(n): | |
if n == 2 or n == 3: | |
return True | |
elif n < 2 or n % 2 == 0: | |
return False | |
elif n < 9: | |
return True | |
elif n % 3 == 0: | |
return False | |
r = int(n**0.5) | |
f = 5 | |
while f <= r: | |
if n % f == 0 or n % (f + 2) == 0: | |
return False | |
else: | |
f += 6 | |
return True | |
def miller_rabin_isprime(a, i, n): | |
""" | |
Miller-Rabin primality test | |
returns a 1 if n is a prime | |
usually i = n - 1 | |
does not test prime 2 | |
""" | |
if i == 0: | |
return 1 | |
x = miller_rabin_isprime(a, i // 2, n) | |
if x == 0: | |
return 0 | |
y = (x * x) % n | |
if ((y == 1) and (x != 1) and (x != (n - 1))): | |
return 0 | |
if (i % 2) != 0: | |
y = (a * y) % n | |
return y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment