Sieve of Eratosthenes

In this lesson, we'll see an efficient algorithm to generate prime numbers.

Generating primes

Given an integer NN, you are asked to print all the prime numbers between 11 and NN.

Using what we have discussed so far, one way to do this would be to iterate over all the numbers from 11 to NN and check if it’s prime or not.

Time Complexity - O(NN).O(N*\sqrt{N}).

It should be okay for NN up to 10410^4 or even 10510^5 but not more.


Sieve of Eratosthenes

The Sieve of Eratosthenes is a simple algorithm to generate all primes from 11 to NN in O(Nlog(logN))O(N*log(logN)).

Steps:

  1. Create a list of all numbers from 22 to NN. Initially, all numbers are unmarked.

  2. Starting from p=2p=2, we will mark all multiples of 22 less than or equal to NN. These numbers are definitely not prime since 22 divides them.

  3. Move to the next unmarked number, i.e., p=3p = 3. Mark all its multiples.

  4. Stop if p>Np>\sqrt{N}

Each unmarked number that we visit is a prime because all non-primes will be marked by one of its factors before we reach this number.

We can use a Boolean array of size NN to distinguish between marked and unmarked numbers.

Let’s understand the process better using the illustration below for N=30N = 30. We will stop after we reach ceil(30)ceil(\sqrt30) i.e 66

Get hands-on with 1200+ tech skills courses.