Skip to content

Instantly share code, notes, and snippets.

@nieldomingo
Created August 6, 2017 06:11
Show Gist options
  • Save nieldomingo/52a2591bb66a0f02fa5ecc62251226bf to your computer and use it in GitHub Desktop.
Save nieldomingo/52a2591bb66a0f02fa5ecc62251226bf to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes using Python Generators
def sieve():
def _sieve():
current = 2
while True:
yield current
current += 1
def _new_gen(s, current_prime):
return (n for n in s if n % current_prime != 0)
s = _sieve()
while True:
current_prime = next(s)
yield current_prime
s = _new_gen(s, current_prime)
s = sieve()
for _ in range(30):
print(next(s))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment