# Algorithms_in_C++: math/sieve_of_eratosthenes.cpp File Reference

sieve_of_eratosthenes.cpp File Reference

Get list of prime numbers using Sieve of Eratosthenes Sieve of Eratosthenes is an algorithm to find the primes that is between 2 to N (as defined in main). More...

`#include <iostream>`
Include dependency graph for sieve_of_eratosthenes.cpp:

## Macros

#define | MAX 10000000

## Functions

void | sieve (uint32_t N)
void | print (uint32_t N)
void | init ()
int | main ()

## Variables

bool | isprime [MAX]

## Detailed Description

Get list of prime numbers using Sieve of Eratosthenes Sieve of Eratosthenes is an algorithm to find the primes that is between 2 to N (as defined in main).

Time Complexity : \(O(N \cdot\log N)\)
Space Complexity : \(O(N)\)

See also
  primes_up_to_billion.cpp prime_numbers.cpp

## Macro Definition Documentation

## MAX

#define MAX 10000000

Maximum number of primes

## Function Documentation

## init()

void init | ( |  | ) |

Initialize the array

{
for (uint32_t i = 1; i < MAX; i++) {
isprime[i] = true;
}
}

## main()

int main | ( |  | ) |

main function

{
uint32_t N = 100;
init();
sieve(N);
print(N);
return 0;
}
Here is the call graph for this function:

## print()

void print | ( | uint32_t | N | ) |

This function prints out the primes to STDOUT

{
for (uint32_t i = 1; i <= N; i++) {
if (isprime[i]) {
std::cout << i << ' ';
}
}
std::cout << std::endl;
}
Here is the call graph for this function:

## sieve()

void sieve | ( | uint32_t | N | ) |

This is the function that finds the primes and eliminates the multiples.

{
isprime[0] = false;
isprime[1] = false;
for (uint32_t i = 2; i <= N; i++) {
if (isprime[i]) {
for (uint32_t j = (i << 1); j <= N; j += i) {
isprime[j] = false;
}
}
}
}

## Variable Documentation

## isprime

bool isprime[MAX]

array to store the primes

print
void print(uint32_t N)
Definition: sieve_of_eratosthenes.cpp:40
init
void init()
Definition: sieve_of_eratosthenes.cpp:52
std::cout
sieve
void sieve(uint32_t N)
Definition: sieve_of_eratosthenes.cpp:25
MAX
#define MAX
Definition: sieve_of_eratosthenes.cpp:16
std::endl
T endl(T... args)
isprime
bool isprime[MAX]
Definition: sieve_of_eratosthenes.cpp:19