Sieve of Eratosthenes
In this lesson, we'll see an efficient algorithm to generate prime numbers.
We'll cover the following
Generating primes
Given an integer , you are asked to print all the prime numbers between and .
Using what we have discussed so far, one way to do this would be to iterate over all the numbers from to and check if it’s prime or not.
Time Complexity -
It should be okay for up to or even but not more.
Sieve of Eratosthenes
The Sieve of Eratosthenes is a simple algorithm to generate all primes from to in .
Steps:
-
Create a list of all numbers from to . Initially, all numbers are unmarked.
-
Starting from , we will mark all multiples of less than or equal to . These numbers are definitely not prime since divides them.
-
Move to the next unmarked number, i.e., . Mark all its multiples.
-
Stop if
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 to distinguish between marked and unmarked numbers.
Let’s understand the process better using the illustration below for . We will stop after we reach i.e
Get hands-on with 1400+ tech skills courses.