Sieve of Eratosthenes

Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number.

Example:

Input : n =10
Output : 2 3 5 7 

Input : n = 20 
Output: 2 3 5 7 11 13 17 19

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 (Ref Wiki).

Following is the algorithm to find all the prime numbers less than or equal to a given integer n by Eratosthenes’ method:

  1. Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n).
  2. Initially, let p equal 2, the first prime number.
  3. Starting from p2, count up in increments of p and mark each of these numbers greater than or equal to p2 itself in the list. These numbers will be p(p+1), p(p+2), p(p+3), etc..
  4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.


When the algorithm terminates, all the numbers in the list that are not marked are prime.

Explanation with Example:
Let us take an example when n = 50. So we need to print all print numbers smaller than or equal to 50.

We create a list of all numbers from 2 to 50.
Sieve1

According to the algorithm we will mark all the numbers which are divisible by 2 and are greater than or equal to the square of it.
sieve2

Now we move to our next unmarked number 3 and mark all the numbers which are multiples of 3 and are greater than or equal to the square of it.
SieveofEratosthenes3

We move to our next unmarked number 5 and mark all multiples of 5 and are greater than or equal to the square of it.
Sieve4

We continue this process and our final table will look like below:
Sieve5

So the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47.

Thanks to Krishan Kumar for providing above explanation.


Implementation:

Following is the implementation of the above algorithm. In the following implementation, a boolean array arr[] of size n is used to mark multiples of prime numbers.

C/C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to print all primes smaller than or equal to
// n using Sieve of Eratosthenes
#include <bits/stdc++.h>
using namespace std;
  
void SieveOfEratosthenes(int n)
{
    // Create a boolean array "prime[0..n]" and initialize
    // all entries it as true. A value in prime[i] will
    // finally be false if i is Not a prime, else true.
    bool prime[n+1];
    memset(prime, true, sizeof(prime));
  
    for (int p=2; p*p<=n; p++)
    {
        // If prime[p] is not changed, then it is a prime
        if (prime[p] == true)
        {
            // Update all multiples of p greater than or 
            // equal to the square of it
            // numbers which are multiple of p and are
            // less than p^2 are already been marked. 
            for (int i=p*p; i<=n; i += p)
                prime[i] = false;
        }
    }
  
    // Print all prime numbers
    for (int p=2; p<=n; p++)
       if (prime[p])
          cout << p << " ";
}
  
// Driver Program to test above function
int main()
{
    int n = 30;
    cout << "Following are the prime numbers smaller "
         << " than or equal to " << n << endl;
    SieveOfEratosthenes(n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to print all primes smaller than or equal to
// n using Sieve of Eratosthenes
  
class SieveOfEratosthenes
{
    void sieveOfEratosthenes(int n)
    {
        // Create a boolean array "prime[0..n]" and initialize
        // all entries it as true. A value in prime[i] will
        // finally be false if i is Not a prime, else true.
        boolean prime[] = new boolean[n+1];
        for(int i=0;i<n;i++)
            prime[i] = true;
          
        for(int p = 2; p*p <=n; p++)
        {
            // If prime[p] is not changed, then it is a prime
            if(prime[p] == true)
            {
                // Update all multiples of p
                for(int i = p*p; i <= n; i += p)
                    prime[i] = false;
            }
        }
          
        // Print all prime numbers
        for(int i = 2; i <= n; i++)
        {
            if(prime[i] == true)
                System.out.print(i + " ");
        }
    }
      
    // Driver Program to test above function
    public static void main(String args[])
    {
        int n = 30;
        System.out.print("Following are the prime numbers ");
        System.out.println("smaller than or equal to " + n);
        SieveOfEratosthenes g = new SieveOfEratosthenes();
        g.sieveOfEratosthenes(n);
    }
}
  
// This code has been contributed by Amit Khandelwal.

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to print all primes smaller than or equal to
# n using Sieve of Eratosthenes
  
def SieveOfEratosthenes(n):
      
    # Create a boolean array "prime[0..n]" and initialize
    #  all entries it as true. A value in prime[i] will
    # finally be false if i is Not a prime, else true.
    prime = [True for i in range(n+1)]
    p = 2
    while (p * p <= n):
          
        # If prime[p] is not changed, then it is a prime
        if (prime[p] == True):
              
            # Update all multiples of p
            for i in range(p * p, n+1, p):
                prime[i] = False
        p += 1
      
    # Print all prime numbers
    for p in range(2, n):
        if prime[p]:
            print p,
  
# driver program
if __name__=='__main__':
    n = 30
    print "Following are the prime numbers smaller",
    print "than or equal to", n
    SieveOfEratosthenes(n)

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to print all primes
// smaller than or equal to n
// using Sieve of Eratosthenes
using System;
  
namespace prime
{
    public class GFG
    {     
                  
        public static void SieveOfEratosthenes(int n)
        {
              
        // Create a boolean array "prime[0..n]" and initialize
        // all entries it as true. A value in prime[i] will
        // finally be false if i is Not a prime, else true.
  
        bool[] prime = new bool[n+1];
          
        for(int i = 0; i < n; i++)
            prime[i] = true;
          
        for(int p = 2; p*p <= n; p++)
        {
            // If prime[p] is not changed,
            // then it is a prime
            if(prime[p] == true)
            {
                // Update all multiples of p
                for(int i = p*p; i <= n; i += p)
                    prime[i] = false;
            }
        }
          
        // Print all prime numbers
        for(int i = 2; i <= n; i++)
        {
            if(prime[i] == true)
                Console.Write(i + " ");
        }
              
        }
          
        // Driver Code
        public static void Main()
        {
            int n = 30;
            Console.WriteLine("Following are the prime numbers");
            Console.WriteLine("smaller than or equal to " + n);
            SieveOfEratosthenes(n);
              
        }
    }
}
  
// This code is contributed by Sam007.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// php program to print all primes smaller
// than or equal to n using Sieve of
// Eratosthenes
  
function SieveOfEratosthenes($n)
{
    // Create a boolean array "prime[0..n]" 
    // and initialize all entries it as true.
    // A value in prime[i] will finally be 
    // false if i is Not a prime, else true.
    $prime = array_fill(0, $n+1, true);
  
    for ($p = 2; $p*$p <= $n; $p++)
    {
          
        // If prime[p] is not changed, 
        // then it is a prime
        if ($prime[$p] == true)
        {
              
            // Update all multiples of p
            for ($i = $p*$p; $i <= $n; $i += $p)
                $prime[$i] = false;
        }
    }
  
    // Print all prime numbers
    for ($p = 2; $p <= $n; $p++)
        if ($prime[$p])
            echo $p." ";
}
  
// Driver Program to test above function
    $n = 30;
    echo "Following are the prime numbers "
     ."smaller than or equal to " .$n."\n" ;
    SieveOfEratosthenes($n);
  
// This code is contributed by mits
?>

chevron_right



Output:

Following are the prime numbers below 30
2 3 5 7 11 13 17 19 23 29

Time complexity : O(n*log(log(n)))

You may also like to see :
Segmented Sieve.
Sieve of Eratosthenes in 0(n) time complexity

References:
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

This article is compiled by Abhinav Priyadarshi and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up