[Algorithms] Sieve Of Eratosthenes
Discover the Sieve of Eratosthenes — an efficient algorithm to find all prime numbers up to a given limit. We'll cover the steps involved, optimizing runtime, and breaking down the code for a clear understanding.
The Problem
We need to find all prime numbers up to a given number n
. A prime number is only divisible by 1 and itself, and there’s a fast, optimized way to find all primes within a range: the Sieve of Eratosthenes.
For instance, if we input 20
, we should get [2, 3, 5, 7, 11, 13, 17, 19]
, representing all prime numbers from 0 to 20.
The Approach
- Initialize an Array: Start with an array of boolean values up to
n
, with each index set totrue
, assuming every number is prime. - Mark Non-Primes: Begin with the number 2 (the first prime) and mark all its multiples as
false
(not prime). Move to the next number markedtrue
(which will be the next prime) and mark all its multiples asfalse
. - Optimize with Square Root: We only need to mark multiples up to
√n
since any larger factors will have already been marked by smaller primes. - Return Primes: After marking, any index still marked
true
represents a prime number.
Summary
The Sieve of Eratosthenes is an optimized algorithm for finding prime numbers up to a given number n
, using a boolean array to track primes and marking off multiples. This method significantly reduces unnecessary checks, making it both performant and easy to implement.