The Wayback Machine - https://web.archive.org/web/20241114170806/https://www.geeksforgeeks.org/sieve-of-eratosthenes/
Open In App

Sieve of Eratosthenes

Last Updated : 08 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
47.43%
59.4K

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.

Following is the algorithm to find all the prime numbers less than or equal to a given integer n by the Eratosthene’s method: 
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 = 100. So, we need to print all prime numbers smaller than or equal to 100. 

We create a list of all numbers from 2 to 100.  

0

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. 

Sieve-of-Eratosthenes-1

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.  

Sieve-of-Eratosthenes-2

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.  

Sieve-of-Eratosthenes-3

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

Sieve-of-Eratosthenes4

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

Sieve-of-Eratosthenes5

So, the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89 and 97.

Implementation: 

C++
// 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.
    vector<bool> prime(n + 1, true);

  for (int p = 2; p * p <= n; p++) {


        // If prime[p] is not c

hanged, 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 Code
int main()
{
    int n = 30;
    cout << "Following are the prime numbers smaller "
         << " than or equal to " << n << endl;
    SieveOfEratosthenes(n);
    return 0;
}
C
// C program to print all primes smaller than or equal to
// n using Sieve of Eratosthenes
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

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])
            printf("%d ",p);
}

// Driver Code
int main()
{
    int n = 30;
    printf("Following are the prime numbers smaller than or equal to %d \n", n);
    SieveOfEratosthenes(n);
    return 0;
}

// This code is contributed by Aditya Kumar (adityakumar129)
Java
// 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 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 i = 2; i <= n; i++) {
            if (prime[i] == true)
                System.out.print(i + " ");
        }
    }

    // Driver Code
    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 is contributed by Aditya Kumar (adityakumar129)
Python
# 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+1):
        if prime[p]:
            print(p)


# Driver code
if __name__ == '__main__':
    n = 30
    print("Following are the prime numbers smaller"),
    print("than or equal to", n)
    SieveOfEratosthenes(n)
C#
// 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.
JavaScript
<script>

// javascript 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.from({length: n+1}, (_, i) => 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 (i = 2; i <= n; i++)
    {
        if (prime[i] == true)
            document.write(i + " ");
    }
}

// Driver Code
var n = 30;
document.write(
    "Following are the prime numbers ");
document.write("smaller than or equal to " + n+"<br>");
sieveOfEratosthenes(n);

// This code is contributed by 29AjayKumar 

</script>
PHP
<?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 Code
    $n = 30;
    echo "Following are the prime numbers "
     ."smaller than or equal to " .$n."\n" ;
    SieveOfEratosthenes($n);

// This code is contributed by mits
?>

Output
Following are the prime numbers smaller  than or equal to 30
2 3 5 7 11 13 17 19 23 29 

Time Complexity: O(N*log(log(N)))
Auxiliary Space: O(N)

You may also like to see:  



Previous Article
Next Article

Similar Reads

How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
Pre-requisite: Sieve of Eratosthenes What is Sieve of Eratosthenes algorithm? In order to analyze it, let's take a number n and the task is to print the prime numbers less than n. Therefore, by definition of Sieve of Eratosthenes, for every prime number, it has to check the multiples of the prime and mark it as composite. This process continues unt
3 min read
Sum of all Primes in a given range using Sieve of Eratosthenes
Given a range [L, R]. The task is to find the sum of all the prime numbers in the given range from L to R both inclusive. Examples: Input : L = 10, R = 20Output : Sum = 60Prime numbers between [10, 20] are:11, 13, 17, 19Therefore, sum = 11 + 13 + 17 + 19 = 60Input : L = 15, R = 25Output : Sum = 59Recommended: Please try your approach on {IDE} first
12 min read
Sieve of Eratosthenes in 0(n) time complexity
The classical Sieve of Eratosthenes algorithm takes O(N log (log N)) time to find all prime numbers less than N. In this article, a modified Sieve is discussed that works in O(N) time.Example : Given a number N, print all prime numbers smaller than N Input : int N = 15 Output : 2 3 5 7 11 13 Input : int N = 20 Output : 2 3 5 7 11 13 17 19 Manipulat
12 min read
Number of unmarked integers in a special sieve
Given an array A containing numbers from 2 to N.. A special type of sieving is done on it . The procedure of sieving is as follows: Create an array with elements as consecutive integers from 2 to N and mark every element in the array as unmarked.Let an integer Q = N and mark all the proper divisors of Q except Q itself in the array.Find the largest
5 min read
Longest sub-array of Prime Numbers using Segmented Sieve
Given an array arr[] of N integers, the task is to find the longest subarray where all numbers in that subarray are prime. Examples: Input: arr[] = {3, 5, 2, 66, 7, 11, 8} Output: 3 Explanation: Maximum contiguous prime number sequence is {2, 3, 5} Input: arr[] = {1, 2, 11, 32, 8, 9} Output: 2 Explanation: Maximum contiguous prime number sequence i
13 min read
Segmented Sieve (Print Primes in a Range)
Given a range [low, high], print all primes in this range? For example, if the given range is [10, 20], then output is 11, 13, 17, 19. A Naive approach is to run a loop from low to high and check each number for primeness. A Better Approach is to precalculate primes up to the maximum limit using Sieve of Eratosthenes, then print all prime numbers i
15 min read
Sieve of Atkin
Given a limit, print all prime numbers smaller than or equal to the given limit. Examples: Input: limit = 10Output: 2, 3, 5, 7 Input: limit = 20Output: 2, 3, 5, 7, 11, 13, 17, 19 Other Approaches: The prime numbers till a limit can be generated using other algorithms, such as: Sieve of Eratosthenes: O(N*log(log(N)))Sieve of Sundaram: O(N*log N) Sie
15+ min read
Bitwise Sieve
Given a number n, print all primes smaller than n.Examples : Input : 30 Output : 2 3 5 7 11 13 17 19 23 29 Input : n = 100 Output : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 We know how to calculate all primes less than n by the Sieve of Eratosthenes. Below is an implementation of Sieve. One optimization in the below im
15+ min read
Segmented Sieve
Given a number n, print all primes smaller than n. For example, if the given number is 10, output 2, 3, 5, 7. Recommended PracticeProduct of PrimesTry It!A Naive approach is to run a loop from 0 to n-1 and check each number for primeness. A Better Approach is to use Simple Sieve of Eratosthenes. [GFGTABS] C++ #include <iostream> #include <
15+ min read
Sieve of Sundaram to print all primes smaller than n
Given a number n, print all primes smaller than or equal to n. Examples:  Input: n = 10Output: 2, 3, 5, 7Input: n = 20Output: 2, 3, 5, 7, 11, 13, 17, 19We have discussed Sieve of Eratosthenes algorithm for the above task.  Below is Sieve of Sundaram algorithm. printPrimes(n)[Prints all prime numbers smaller than n]1) In general Sieve of Sundaram, p
10 min read
Prime Factorization using Sieve O(log n) for multiple queries
We can calculate the prime factorization of a number "n" in O(sqrt(n)) as discussed here. But O(sqrt n) method times out when we need to answer multiple queries regarding prime factorization.In this article, we study an efficient method to calculate the prime factorization using O(n) space and O(log n) time complexity with pre-computation allowed.
11 min read
Linked List Data Structure
A linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Here’s the comparison of Linked List vs Arrays Linked List: Data Structure: Non-contiguous Memory Allocation:
3 min read
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements in an order. Sorting is provided in library implementation of most of the programming languages. Basics of Sorting Algorithms:Introduction to Sorting Applications of Sorting Sorting Algorithms:Comparison Based : Selection Sort, Bubble Sort, Insertion Sort, Merge Sort, Quick
3 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. In this tutorial, we will explore the most commonly used data structures, including arrays, linke
10 min read
Learn Data Structures and Algorithms | DSA Tutorial
Data Structures and Algorithms (DSA) refer to the study of methods for organizing and storing data and the design of procedures (algorithms) for solving problems, which operate on these data structures. DSA is one of the most important skills that every computer science student must have. It is often seen that people with good knowledge of these te
15+ min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of the node. The AVL tree is named after its inventors, Georgy
3 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the first pass, the maximum element goes to end (its cor
8 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element and swap it with the first element. This way we get
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Table of Content What is Binary Search Algorithm?Conditions to apply Binary Search Algorithm in a Data St
15+ min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. Table of Content How does QuickSort Algorithm work? Working of Partition Algorithm with IllustrationIllustration of QuickSort Algor
13 min read
Heap Sort - Data Structures and Algorithms Tutorials
Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use Binary Heap so that we can quickly find and move t
15 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a sorting algorithm that follows the divide-and-conquer approach. It works by recursively dividing the input array into smaller subarrays and sorting those subarrays then merging them back together to obtain the sorted array. In simple terms, we can say that the process of merge sort is to divide the array into two halves, sort each h
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. Then, you pick a card from the unsorted group and p
10 min read
How to find Shortest Paths from Source to all Vertices using Dijkstra's Algorithm
Given a weighted graph and a source vertex in the graph, find the shortest paths from the source to all the other vertices in the given graph. Note: The given graph does not contain any negative edge. Examples: Input: src = 0, the graph is shown below. Output: 0 4 12 19 21 11 9 8 14 Explanation: The distance from 0 to 1 = 4. The minimum distance fr
15+ min read
Prim’s Algorithm for Minimum Spanning Tree (MST)
Introduction to Prim's algorithm:We have discussed Kruskal's algorithm for Minimum Spanning Tree. Like Kruskal's algorithm, Prim’s algorithm is also a Greedy algorithm. This algorithm always starts with a single node and moves through several adjacent nodes, in order to explore all of the connected edges along the way. The algorithm starts with an
15+ min read
Kruskal’s Minimum Spanning Tree (MST) Algorithm
A minimum spanning tree (MST) or minimum weight spanning tree for a weighted, connected, undirected graph is a spanning tree with a weight less than or equal to the weight of every other spanning tree. To learn more about Minimum Spanning Tree, refer to this article. Introduction to Kruskal's Algorithm:Here we will discuss Kruskal's algorithm to fi
15+ min read
Breadth First Search or BFS for a Graph
Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a node, then first traverses all its adjacent. Once all adjacent are visited, then their adjacent are traversed. This is different from DFS in a way that closest vertices are visited before others. We mainly traverse vertices level by level. A lot of popular graph
15+ min read
0/1 Knapsack Problem
Prerequisites: Introduction to Knapsack Problem, its Types and How to solve them Given N items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum
15+ min read
Depth First Search or DFS for a Graph
Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. Like trees, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. After we finish traversing one adjacent vertex and its reachable vertices,
15+ min read
Tree Traversal Techniques
Tree Traversal techniques include various ways to visit all the nodes of the tree. Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. In this article, we will discuss about all the tree traversal techniques along with their uses. Table o
15+ min read
three90RightbarBannerImg