TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
sieve_of_eratosthenes.cpp
Go to the documentation of this file.
1
15#include <cstdint>
16#include <cassert>
17#include <iostream>
18#include <vector>
19
24namespace math {
29namespace sieve_of_eratosthenes {
45std::vector<bool> sieve(uint32_t N) {
46 std::vector<bool> is_prime(N + 1, true); // Initialize all as prime numbers
47 is_prime[0] = is_prime[1] = false; // 0 and 1 are not prime numbers
48
49 for (uint32_t i = 2; i * i <= N; i++) {
50 if (is_prime[i]) {
51 for (uint32_t j = i * i; j <= N; j += i) {
52 is_prime[j] = false;
53 }
54 }
55 }
56 return is_prime;
57}
58
65void print(uint32_t N, const std::vector<bool> &is_prime) {
66 for (uint32_t i = 2; i <= N; i++) {
67 if (is_prime[i]) {
68 std::cout << i << ' ';
69 }
70 }
71 std::cout << std::endl;
72}
73
74} // namespace sieve_of_eratosthenes
75} // namespace math
76
81static void tests() {
82 std::vector<bool> is_prime_1 =
83 math::sieve_of_eratosthenes::sieve(static_cast<uint32_t>(10));
84 std::vector<bool> is_prime_2 =
85 math::sieve_of_eratosthenes::sieve(static_cast<uint32_t>(20));
86 std::vector<bool> is_prime_3 =
87 math::sieve_of_eratosthenes::sieve(static_cast<uint32_t>(100));
88
89 std::vector<bool> expected_1{false, false, true, true, false, true,
90 false, true, false, false, false};
91 assert(is_prime_1 == expected_1);
92
93 std::vector<bool> expected_2{false, false, true, true, false, true,
94 false, true, false, false, false, true,
95 false, true, false, false, false, true,
96 false, true, false};
97 assert(is_prime_2 == expected_2);
98
99 std::vector<bool> expected_3{
100 false, false, true, true, false, true, false, true, false, false,
101 false, true, false, true, false, false, false, true, false, true,
102 false, false, false, true, false, false, false, false, false, true,
103 false, true, false, false, false, false, false, true, false, false,
104 false, true, false, true, false, false, false, true, false, false,
105 false, false, false, true, false, false, false, false, false, true,
106 false, true, false, false, false, false, false, true, false, false,
107 false, true, false, true, false, false, false, false, false, true,
108 false, false, false, true, false, false, false, false, false, true,
109 false, false, false, false, false, false, false, true, false, false,
110 false};
111 assert(is_prime_3 == expected_3);
112
113}
114
119int main() {
120 tests();
121 return 0;
122}
for assert
void sieve(std::vector< bool > *vec)
Performs the sieve.
bool is_prime(int64_t num)
Function to check if the given number is prime or not.
Functions for finding Prime Numbers using Sieve of Eratosthenes.
static void tests()
Self-test implementations.
int main()
Main function.