Skip to content

Instantly share code, notes, and snippets.

@sandeepnmenon
Last active August 11, 2021 07:09
Show Gist options
  • Save sandeepnmenon/57c462fe92b5d668e0e3773fccffb24c to your computer and use it in GitHub Desktop.
Save sandeepnmenon/57c462fe92b5d668e0e3773fccffb24c to your computer and use it in GitHub Desktop.
Prime number generator using lazy Sieve of Eratosthenes
def natural_number_generator(n):
yield n
yield from natural_number_generator(n+1)
def sieve_of_eratosthenes(number_list):
next_prime = next(number_list)
yield next_prime
yield from sieve_of_eratosthenes(i for i in number_list if i%next_prime != 0)
if __name__ == '__main__':
# Number of primes to generate
range_limit = 100
# Sieve prime numbers
prime_generator = sieve_of_eratosthenes(natural_number_generator(2))
for i in range(range_limit):
print(next(prime_generator))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment