The Wayback Machine - https://web.archive.org/web/20240815161531/https://www.geeksforgeeks.org/c-program-for-sieve-of-eratosthenes/
Open In App

C++ Program for Sieve of Eratosthenes

Last Updated : 12 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a number n, print all primes smaller than or equal to n. It is also given that n is a small number. For example, if n is 10, the output should be “2, 3, 5, 7”. If n is 20, the output should be “2, 3, 5, 7, 11, 13, 17, 19”.

CPP
// 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
            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;
}

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(long))
Auxiliary Space : O ( 1 )

Please refer complete article on Sieve of Eratosthenes for more details!


Previous Article
Next Article

Similar Reads

C Program for Program to Interchange Diagonals of Matrix
Write a C program for a given square matrix of order n*n, the task is to interchange the elements of both diagonals. Examples : Input : matrix[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : matrix[][] = {3, 2, 1, 4, 5, 6, 9, 8, 7} Input : matrix[][] = {4, 2, 3, 1, 5, 7, 6, 8, 9, 11, 10, 12, 16, 14, 15, 13} Output : matrix[][] = {1, 2, 3, 4, 5, 6, 7, 8,
2 min read
C++ Program For Detecting Loop In A Linked List
Given a linked list, check if the linked list has loop or not. Below diagram shows a linked list with a loop. The following are different ways of doing this. Solution 1: Hashing Approach: Traverse the list one by one and keep putting the node addresses in a Hash Table. At any point, if NULL is reached then return false, and if the next of the curre
11 min read
C++ Program to concatenate two strings using Operator Overloading
Pre-requisite: Operator Overloading in C++Given two strings. The task is to concatenate the two strings using Operator Overloading in C++. Example: Input: str1 = "hello", str2 = "world" Output: helloworld Input: str1 = "Geeks", str2 = "World" Output: GeeksWorld Approach 1: Using unary operator overloading. To concatenate two strings using unary ope
3 min read
C++ Program for ShellSort
In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h'th element is sorted. C/C++ Code // C++ implementation of Shell Sort #include &lt;iostream&gt; /* function to sort arr using shellSort */ void shellSort(int arr[], int n) { /
2 min read
C++ Program for Longest Common Subsequence
LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, "abc", "abg", "bdf", "aeg", '"acefg", .. etc are subsequences of "abcdefg". So a string of length n has 2^n different possible s
3 min read
C++ Program for Longest Increasing Subsequence
The Longest Increasing Subsequence (LIS) problem is to find the length of the longest subsequence of a given sequence such that all elements of the subsequence are sorted in increasing order. For example, the length of LIS for {10, 22, 9, 33, 21, 50, 41, 60, 80} is 6 and LIS is {10, 22, 33, 50, 60, 80}. Examples: Input : arr[] = {3, 10, 2, 1, 20} O
9 min read
C++ Program for GCD of more than two (or array) numbers
The GCD of three or more numbers equals the product of the prime factors common to all the numbers, but it can also be calculated by repeatedly taking the GCDs of pairs of numbers. gcd(a, b, c) = gcd(a, gcd(b, c)) = gcd(gcd(a, b), c) = gcd(gcd(a, c), b) C/C++ Code // C++ program to find GCD of two or // more numbers #include &lt;bits/stdc++.h&gt; u
3 min read
C++ Program for Common Divisors of Two Numbers
Given two integer numbers, the task is to find the count of all common divisors of given numbers. Input : a = 12, b = 24 Output: 6 // all common divisors are 1, 2, 3, // 4, 6 and 12 Input : a = 3, b = 17 Output: 1 // all common divisors are 1 Input : a = 20, b = 36 Output: 3 // all common divisors are 1, 2, 4 // C++ implementation of program #inclu
2 min read
C++ Program for Bitonic Sort
Bitonic Sequence A sequence is called Bitonic if it is first increasing, then decreasing. In other words, an array arr[0..n-i] is Bitonic if there exists an index i where 0&lt;=i&lt;=n-1 such that x0 &lt;= x1 â€Ķ..&lt;= xi and xi &gt;= xi+1â€Ķ.. &gt;= xn-1 A sequence, sorted in increasing order is considered Bitonic with the decreasing part as empty. S
4 min read
C++ Program for Recursive Bubble Sort
Background: Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. Following is the iterative Bubble sort algorithm : // Iterative Bubble Sort bubbleSort(arr[], n) { for (i = 0; i n-1; i++) // Last i elements are already in place for (j = 0; j &lt; n-i-1; j++) swap(arr[j
2 min read
C++ Program for BogoSort or Permutation Sort
BogoSort also known as permutation sort, stupid sort, slow sort, shotgun sort or monkey sort is a particularly ineffective algorithm based on generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted.(Wiki) For example, if bogosort is used to sort a deck of cards, it would consist o
2 min read
C++ Program for Gnome Sort
Algorithm Steps If you are at the start of the array then go to the right element (from arr[0] to arr[1]).If the current array element is larger or equal to the previous array element then go one step right if (arr[i] &gt;= arr[i-1]) i++;If the current array element is smaller than the previous array element then swap these two elements and go one
2 min read
C++ Program for Zeckendorf\'s Theorem (Non-Neighbouring Fibonacci Representation)
Given a number, find a representation of number as sum of non-consecutive Fibonacci numbers.Examples: Input: n = 10 Output: 8 2 8 and 2 are two non-consecutive Fibonacci Numbers and sum of them is 10. Input: n = 30 Output: 21 8 1 21, 8 and 1 are non-consecutive Fibonacci Numbers and sum of them is 30. The idea is to use Greedy Algorithm. 1) Let n b
2 min read
C++ Program for How to check if a given number is Fibonacci number?
Given a number 'n', how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .. Examples : Input : 8 Output : Yes Input : 34 Output : Yes Input : 41 Output : No Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or n
2 min read
C++ Program for Range sum queries without updates
Given an array arr of integers of size n. We need to compute sum of elements from index i to index j. The queries consisting of i and j index values will be executed multiple times. Examples: Input : arr[] = {1, 2, 3, 4, 5} i = 1, j = 3 i = 2, j = 4 Output : 9 12 Input : arr[] = {1, 2, 3, 4, 5} i = 0, j = 4 i = 1, j = 2 Output : 15 5 C/C++ Code //
2 min read
C++ Program to Split the array and add the first part to the end
There is a given an array and split it from a specified position, and move the first part of array add to the end. Examples: Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end . Input : arr[] = {3, 1, 2} k = 1 Output : arr[] = {1, 2, 3} Explana
2 min read
C++ Program for Largest K digit number divisible by X
Integers X and K are given. The task is to find highest K-digit number divisible by X. Examples: Input : X = 30, K = 3 Output : 990 990 is the largest three digit number divisible by 30. Input : X = 7, K = 2 Output : 98 An efficient solution is to use below formula. ans = MAX - (MAX % X) where MAX is the largest K digit number which is 999...K-time
1 min read
C++ Program for Smallest K digit number divisible by X
Integers X and K are given. The task is to find the smallest K-digit number divisible by X. Examples: Input : X = 83, K = 5 Output : 10043 10040 is the smallest 5 digit number that is multiple of 83. Input : X = 5, K = 2 Output : 10 An efficient solution would be : Compute MIN : smallest K-digit number (1000...K-times) If, MIN % X is 0, ans = MIN e
2 min read
C++ Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!
You have been given a series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!, find out the sum of the series till nth term. Examples: Input :n = 5 Output : 2.70833 Input :n = 7 Output : 2.71806 C/C++ Code /*CPP program to print the sum of series */ #include &amp;lt;bits/stdc++.h&amp;gt; using namespace std; /*function to calculate sum of given series*/ do
1 min read
C++ Program to Print Matrix in Z form
Given a square matrix of order n*n, we need to print elements of the matrix in Z form Examples: Input : mat[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : 1 2 3 5 7 8 9 Input : mat[][] = {5, 19, 8, 7, 4, 1, 14, 8, 2, 20, 1, 9, 1, 2, 55, 4} Output: 5 19 8 7 14 20 1 2 55 4 C/C++ Code // CPP program to print a square matrix in Z form #include &lt;bits/std
2 min read
C++ Program for Stooge Sort
The Stooge sort is a recursive sorting algorithm. It is defined as below (for ascending order sorting). Step 1 : If value at index 0 is greater than value at last index, swap them. Step 2: Recursively, a) Stooge sort the initial 2/3rd of the array. b) Stooge sort the last 2/3rd of the array. c) Stooge sort the initial 2/3rd again to confirm. C/C++
2 min read
C++ Program for Comb Sort
Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values. So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using gap of size more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration until it reaches the value 1. Thus Comb Sort removes more
2 min read
C++ Program for Cocktail Sort
Cocktail Sort is a variation of Bubble sort. The Bubble sort algorithm always traverses elements from left and moves the largest element to its correct position in first iteration and second largest in second iteration and so on. Cocktail Sort traverses through a given array in both directions alternatively. Algorithm: Each iteration of the algorit
3 min read
Program to generate random alphabets
Prerequisite : rand() and srand() Given all alphabets in a character array, print a string of random characters of given size.We will use rand() function to print random characters. It returns random integer values. This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. A ubiquitou
4 min read
C program to print employee details using Structure
In this program, we will read and display details of n employees using Structure. Employee details like Name, age, phone number, salary will be printed. Method : Declare variables using Structure Read details of all employees like employee name, age, phone number and salary. Display all the details of employees Below is CPP program showing employee
2 min read
C++ Program for Sum of squares of first n natural numbers
Given a positive integer N. The task is to find 12 + 22 + 32 + ..... + N2. Examples: Input : N = 4 Output : 30 12 + 22 + 32 + 42 = 1 + 4 + 9 + 16 = 30 Input : N = 5 Output : 55 Method 1: O(N) The idea is to run a loop from 1 to n and for each i, 1 2 to sum. C/C++ Code // CPP Program to find sum of square of first n natural numbers #include &lt;bits
4 min read
C++ program to generate random number
The below implementation is to generate random number from 1 to given limit. The below function produces behavior similar to srand() function. Prerequisite : random header in C++ | Set 1(Generators) // C++ program to generate random number #include &lt;bits/stdc++.h&gt; using namespace std; // Function with return random number from 1 to // given l
1 min read
C++ Program to find sum of even factors of a number
Given a number n, the task is to find the even factor sum of a number. Examples: Input : 30 Output : 48 Even dividers sum 2 + 6 + 10 + 30 = 48 Input : 18 Output : 26 Even dividers sum 2 + 6 + 18 = 26 Let p1, p2, â€Ķ pk be prime factors of n. Let a1, a2, .. ak be highest powers of p1, p2, .. pk respectively that divide n, i.e., we can write n as n = (
3 min read
C++ program for Solving Cryptarithmetic Puzzles
Newspapers and magazines often have crypt-arithmetic puzzles of the form: Examples: Input : s1 = SEND, s2 = "MORE", s3 = "MONEY" Output : One of the possible solution is: D=1 E=5 M=0 N=3 O=8 R=2 S=7 Y=6 Explanation: The above values satisfy below equation : SEND + MORE -------- MONEY -------- It is strongly recommended to refer Backtracking | Set 8
4 min read
C++ Program for Topological Sorting
Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is not possible if the graph is not a DAG. For example, a topological sorting of the following graph is "5 4 2 3 1 0". There can be more than one topolog
3 min read
Article Tags :
three90RightbarBannerImg