Skip to content

Instantly share code, notes, and snippets.

@iepathos
Last active December 17, 2015 12:59
Show Gist options
  • Save iepathos/5614314 to your computer and use it in GitHub Desktop.
Save iepathos/5614314 to your computer and use it in GitHub Desktop.
Python Primal Number functions
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