Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
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:

Functions

void sieve (uint32_t N, bool *isprime)
 
void print (uint32_t N, const bool *isprime)
 
int main ()
 

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

Function Documentation

◆ main()

int main ( )

Main function

50  {
51  uint32_t N = 100;
52  bool *isprime = new bool[N];
53  sieve(N, isprime);
54  print(N, isprime);
55  delete[] isprime;
56 
57  return 0;
58 }
Here is the call graph for this function:

◆ print()

void print ( uint32_t  N,
const bool *  isprime 
)

This function prints out the primes to STDOUT

Parameters
Nnumber of primes to check
[in]isprimea boolean array of size N identifying if i^th number is prime or not
38  {
39  for (uint32_t i = 2; i <= N; i++) {
40  if (!isprime[i]) {
41  std::cout << i << ' ';
42  }
43  }
45 }
Here is the call graph for this function:

◆ sieve()

void sieve ( uint32_t  N,
bool *  isprime 
)

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

Parameters
Nnumber of primes to check
[out]isprimea boolean array of size N identifying if i^th number is prime or not
21  {
22  isprime[0] = true;
23  isprime[1] = true;
24  for (uint32_t i = 2; i * i <= N; i++) {
25  if (!isprime[i]) {
26  for (uint32_t j = (i << 1); j <= N; j = j + i) {
27  isprime[j] = true;
28  }
29  }
30  }
31 }
print
void print(uint32_t N, const bool *isprime)
Definition: sieve_of_eratosthenes.cpp:38
std::cout
sieve
void sieve(uint32_t N, bool *isprime)
Definition: sieve_of_eratosthenes.cpp:21
std::endl
T endl(T... args)
isprime
bool isprime[1000006]
Definition: prime_factorization.cpp:13