Sieve of Eratosthenes
Understand how the Sieve of Eratosthenes algorithm efficiently identifies prime numbers up to a given limit. This lesson helps you implement a prime detection method that marks multiples of primes as non-prime, optimizing your number theory problem-solving skills for coding interviews.
We'll cover the following...
The Sieve of Eratosthenes approach
We can improve our solution and have a low time complexity as compared to the previous solution that we discussed. The Sieve of Eratosthenes is one of the most efficient ways to find all primes smaller than N when N is smaller than 10 million or so.
We can use a Sieve of Numbers up to N. For all prime numbers <= sqrt(N), we can make their multiple non-prime, i.e., if p is prime, 2p, 3p, … so on will be non-prime.
Let us look at an illustration to understand the approach better.
So now you must have an idea of how this approach works. Let us start the implementation of this approach.
Explanation:
- On line 6, we created our Sieve of Numbers
psuch that the value stored at the index ofpwill denote whetheriis a prime or not. - On line 7, we ran a loop to mark all the numbers as prime initially.
- From lines 9 to 14, we ran a loop to mark all the multiples of
i— that are less than or equal to N — as non-prime. We do this only if the numberiis marked as a prime in our sieve arrayp. - On lines 15 and 16, we finally mark
0and1as non-prime. - On line 17, we returned
trueorfalsebased on whether the number is marked as prime or not in our sieve.