In this post, we will see how to find prime numbers using the Sieve of Eratosthenes.

Prime numbers are natural numbers that have exactly two distinct factors: 1 and themselves. For example, 2, 3, 5, 7, 11, and 13 are prime numbers, but 4, 6, 8, 9, 10, and 12 are not. Finding prime numbers is an important problem in mathematics and computer science, as they have many applications in cryptography, number theory, and algorithms. The Sieve of Eratosthenes is a simple and elegant algorithm that can find all the prime numbers up to a given limit in a fast and efficient way.

Practice this problem

1. Overview and Working of Sieve of Eratosthenes

The Sieve of Eratosthenes algorithm works by iteratively marking as composite (not prime) the multiples of each prime number, starting from 2. The remaining unmarked numbers are primes. The algorithm can be visualized as follows:

  • Create a list of consecutive integers from 2 to n, where n is the upper limit.
  • Let p be the first unmarked number in the list, which is 2 initially.
  • Mark all the multiples of p from p^2 to n as composite. For example, if p is 2, mark 4, 6, 8, …, n as composite.
  • Find the next unmarked number in the list that is greater than p and assign it to p. If there is no such number, stop.
  • Repeat steps 3 and 4 until p^2 is greater than n.

2. Implementation of Sieve of Eratosthenes

One way to implement the Sieve of Eratosthenes is to use a boolean array to keep track of whether a number is marked or not. Here is a simple function that returns a list of all primes up to n using this method. For example, primes less than n = 50 are [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47].

C++


Java


Python



3. Speed and Memory Optimizations for Sieve of Eratosthenes

The basic implementation of the Sieve of Eratosthenes can be improved in several ways to make it faster and more memory-efficient. Here are some common optimizations:

  • Start marking multiples from p^2 instead of p. This is because all the smaller multiples of p have already been marked by previous primes.
  • Use only odd numbers in the list. This is because all even numbers except for 2 are composite. This reduces the size of the array by half and also eliminates half of the iterations.
  • Use a bit array instead of a boolean array. This reduces the space complexity by a factor of 8, as each bit can store the value of one number instead of one byte.

Here is a modified function that implements these optimizations:

C++


Java


Python