Skip to contentKEEP THE CRAFTTHE SANCTUARY

Generate Primes with a Sieve

List every prime up to a limit with the Sieve of Eratosthenes: cross out the multiples of each prime, starting at its square.

The problem

Implement primes_up_to(limit) and return every prime number less than or equal to limit, in increasing order. Use the Sieve of Eratosthenes: treat every number from 2 to limit as prime at first, then for each number that is still marked prime, cross out its multiples. The numbers left at the end are the primes. Example: primes_up_to(30) returns [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]. If limit is below 2, return [].

Starter code

def primes_up_to(limit):
    pass

Public examples

  1. limit = 30gives[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
  2. limit = 1gives[]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.