I was Googling for a 'correct' or 'efficient' implementation of the Sieve of Eratosthenes. I found them all more complicated than what I came up with. I am by no means a Python expert, so I was wondering if something is wrong with my code.
def get_primes(max_int): numbers = range(2, max_int) while len(numbers) > 0: numbers = [ num for num in numbers if num % numbers != 0 or num == numbers ] # only keep numbers that are NOT divisible by the prime yield numbers # yield the prime numbers = numbers[1:] # make a new numbers-array, the first num is a new prime
Call it with
primes = get_primes(1000)
And it gives you a generator of primes up until 1000.