TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
eratosthenes.cpp
Go to the documentation of this file.
1
15
16
#include <cassert>
17
#include <chrono>
18
#include <iostream>
19
#include <string>
20
#include <vector>
21
26
namespace
math
{
33
void
sieve
(std::vector<bool> *vec) {
34
(*vec)[0] =
false
;
35
(*vec)[1] =
false
;
36
37
// The sieve sets values to false as they are found not prime
38
for
(uint64_t n = 2; n < vec->size(); n++) {
39
for
(uint64_t multiple = n << 1; multiple < vec->size();
40
multiple += n) {
41
(*vec)[multiple] =
false
;
42
}
43
}
44
}
45
51
void
print_primes
(std::vector<bool>
const
&
primes
) {
52
for
(uint64_t i = 0; i <
primes
.size(); i++) {
53
if
(
primes
[i]) {
54
std::cout << i << std::endl;
55
}
56
}
57
}
58
}
// namespace math
59
64
static
void
test
() {
65
auto
primes
= std::vector<bool>(10,
true
);
66
math::sieve
(&
primes
);
67
assert(
primes
[0] ==
false
);
68
assert(
primes
[1] ==
false
);
69
assert(
primes
[2] ==
true
);
70
assert(
primes
[3] ==
true
);
71
assert(
primes
[4] ==
false
);
72
assert(
primes
[5] ==
true
);
73
assert(
primes
[6] ==
false
);
74
assert(
primes
[7] ==
true
);
75
assert(
primes
[8] ==
false
);
76
assert(
primes
[9] ==
false
);
77
78
std::cout <<
"All tests have successfully passed!\n"
;
79
}
80
87
int
main
(
int
argc,
char
*argv[]) {
88
test
();
// run self-test implementations
89
90
// The largest prime we will check for
91
auto
max = 10000;
92
93
// Store a boolean for every number which states if that index is prime or
94
// not
95
auto
primes
= std::vector<bool>(max,
true
);
96
97
// Store the algorithm start time
98
auto
start = std::chrono::high_resolution_clock::now();
99
100
// Run the sieve
101
math::sieve
(&
primes
);
102
103
// Time difference calculation
104
auto
time = std::chrono::duration_cast<
105
std::chrono::duration<double, std::ratio<1>>>(
106
std::chrono::high_resolution_clock::now() - start)
107
.count();
108
109
// Print the primes if we see that "print" was passed as an arg
110
if
(argc > 1 && argv[1] == std::string(
"print"
)) {
111
math::print_primes
(
primes
);
112
}
113
114
// Print the time taken we found earlier
115
std::cout <<
"Time taken: "
<< time <<
" seconds"
<< std::endl;
116
117
return
0;
118
}
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
math
for assert
math::sieve
void sieve(std::vector< bool > *vec)
Performs the sieve.
Definition
eratosthenes.cpp:33
math::print_primes
void print_primes(std::vector< bool > const &primes)
Prints all the indexes of true values in the passed std::vector.
Definition
eratosthenes.cpp:51
primes
std::vector< int > primes(size_t max)
Definition
prime_numbers.cpp:12
math
eratosthenes.cpp
Generated by
1.18.0