text: Sieve of Eratosthenes | C ++ program to print all primes smaller than or equal to n using Sieve of Eratosthenes ; 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 . ; If prime [ p ] is not changed , then it is a prime ; 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 . ; Print all prime numbers ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void SieveOfEratosthenes ( int n ) { bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } for ( int p = 2 ; p <= n ; p ++ ) if ( prime [ p ] ) cout << p << " ▁ " ; } int main ( ) { int n = 30 ; cout << " Following ▁ are ▁ the ▁ prime ▁ numbers ▁ smaller ▁ " << " ▁ than ▁ or ▁ equal ▁ to ▁ " << n << endl ; SieveOfEratosthenes ( n ) ; return 0 ; }