Last active
December 17, 2015 12:59
-
-
Save iepathos/5614314 to your computer and use it in GitHub Desktop.
Python Primal Number functions
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, sys | |
""" | |
Miller Rabin Probabilistic Primality Test | |
""" | |
def miller_rabin_pass(a, s, d, n): | |
a_to_power = pow(a, d, n) | |
if a_to_power == 1: | |
return True | |
for i in xrange(s-1): | |
if a_to_power == n - 1: | |
return True | |
a_to_power = (a_to_power * a_to_power) % n | |
return a_to_power == n - 1 | |
def miller_rabin(n): | |
# compute s and d | |
d = n - 1 | |
s = 0 | |
# Using bit shifts to compute d rapidly, and only test its least | |
# significant bit to determine if it is odd | |
while d % 2 == 0: | |
d >>= 1 | |
s += 1 | |
# 20 times is enough to make the 1/4^k error rate negligible | |
for repeat in xrange(20): | |
a = 0 | |
while a == 0: | |
a = random.randrange(n) | |
if not miller_rabin_pass(a, s, d, n): | |
return False | |
return True | |
def findPrimes(num_set): | |
""" | |
Takes a number set and returns a list of the primes in that set. | |
Using set() to remove any duplicates that may be passed in to it. | |
""" | |
return [x for x in set(num_set) if miller_rabin(x)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment