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:

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

52  {
53  for (uint32_t i = 1; i < MAX; i++) {
54  isprime[i] = true;
55  }
56 }

◆ main()

int main ( )

main function

59  {
60  uint32_t N = 100;
61  init();
62  sieve(N);
63  print(N);
64  return 0;
65 }
Here is the call graph for this function:

◆ print()

void print ( uint32_t  N)

This function prints out the primes to STDOUT

40  {
41  for (uint32_t i = 1; i <= N; i++) {
42  if (isprime[i]) {
43  std::cout << i << ' ';
44  }
45  }
47 }
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.

25  {
26  isprime[0] = false;
27  isprime[1] = false;
28  for (uint32_t i = 2; i <= N; i++) {
29  if (isprime[i]) {
30  for (uint32_t j = (i << 1); j <= N; j += i) {
31  isprime[j] = false;
32  }
33  }
34  }
35 }

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