Created
September 14, 2012 11:54
-
-
Save hayd/3721517 to your computer and use it in GitHub Desktop.
Primes generator function
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
class primes(): | |
def __init__(self): | |
self.primes_list = [2,3] | |
self.generator = self.generator() | |
def _append_if_no_prime_divides(self,q): | |
is_prime = not any( q % p == 0 for p in self.primes_list) | |
if is_prime: | |
self.primes_list.append(q) | |
return is_prime | |
def generator(self): | |
yield 2; yield 3 | |
m = 1 | |
while True: | |
q1 = 6*m - 1 | |
q2 = 6*m + 1 | |
if self._append_if_no_prime_divides(q1): | |
yield q1 | |
if self._append_if_no_prime_divides(q2): | |
yield q2 | |
m+=1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Much more efficient algorithm here: http://macdevcenter.com/pub/a/python/excerpt/pythonckbk_chap1/index1.html?page=2