Last active
August 29, 2015 14:26
-
-
Save vterron/fad0edf72e4d31aeff0c to your computer and use it in GitHub Desktop.
Prime generator via unbounded Sieve of Erathosthenes
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
#! /usr/bin/env python3 | |
""" See this URL for an explanation of what we're doing here: | |
https://wthwdik.wordpress.com/2007/08/30/an-unbounded-sieve-of-eratosthenes/ | |
""" | |
import itertools | |
import types | |
class Prime(types.SimpleNamespace): | |
def __new__(cls, n, multiple): | |
return super().__new__(cls, n=n, multiple=multiple) | |
def update_multiple(self, value): | |
""" Increase 'multiple' in steps of 'n' until it is >= value. """ | |
while self.multiple < value: | |
self.multiple += self.n | |
def get_primes(): | |
""" Prime generator via unbounded Sieve of Erathosthenes. """ | |
yield 2 | |
prime_numbers = [Prime(n=2, multiple=2)] | |
for candidate in itertools.count(3, step=2): | |
for prime in prime_numbers: | |
prime.update_multiple(candidate) | |
if candidate == prime.multiple: | |
break | |
else: | |
yield candidate | |
prime_numbers.append(Prime(n=candidate, multiple=candidate)) | |
if __name__ == "__main__": | |
n = 9 # find the tenth prime number | |
it = itertools.islice(get_primes(), n, n + 1) | |
print(next(it)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment