TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
Prime Numbers using Sieve of Eratosthenes More...
#include <cstdint>
#include <cassert>
#include <iostream>
#include <vector>
Go to the source code of this file.
Namespaces | |
namespace | math |
for assert | |
namespace | sieve_of_eratosthenes |
Functions for finding Prime Numbers using Sieve of Eratosthenes. | |
Functions | |
std::vector< bool > | math::sieve_of_eratosthenes::sieve (uint32_t N) |
Function to sieve out the primes. | |
void | math::sieve_of_eratosthenes::print (uint32_t N, const std::vector< bool > &is_prime) |
Function to print the prime numbers. | |
static void | tests () |
Self-test implementations. | |
int | main () |
Main function. | |
Prime Numbers using Sieve of Eratosthenes
Sieve of Eratosthenes is an algorithm that finds all the primes between 2 and N.
Time Complexity : \(O(N \cdot\log \log N)\)
Space Complexity : \(O(N)\)
Definition in file sieve_of_eratosthenes.cpp.
int main | ( | void | ) |
Main function.
Definition at line 119 of file sieve_of_eratosthenes.cpp.
void math::sieve_of_eratosthenes::print | ( | uint32_t | N, |
const std::vector< bool > & | is_prime ) |
Function to print the prime numbers.
N | number till which primes are to be found |
is_prime | a vector of N + 1 booleans identifying if i ^th number is a prime or not |
Definition at line 65 of file sieve_of_eratosthenes.cpp.
std::vector< bool > math::sieve_of_eratosthenes::sieve | ( | uint32_t | N | ) |
Function to sieve out the primes.
This function finds all the primes between 2 and N using the Sieve of Eratosthenes algorithm. It starts by assuming all numbers (except zero and one) are prime and then iteratively marks the multiples of each prime as non-prime.
Contains a common optimization to start eliminating multiples of a prime p starting from p * p since all of the lower multiples have been already eliminated.
N | number till which primes are to be found |
N + 1
booleans identifying if i
^th number is a prime or not Definition at line 45 of file sieve_of_eratosthenes.cpp.
|
static |
Self-test implementations.
Definition at line 81 of file sieve_of_eratosthenes.cpp.