TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
eratosthenes.cpp
Go to the documentation of this file.
1
16#include <cassert>
17#include <chrono>
18#include <iostream>
19#include <string>
20#include <vector>
21
26namespace math {
33void 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
51void 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
64static void test() {
65 auto primes = std::vector<bool>(10, true);
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
87int 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
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")) {
112 }
113
114 // Print the time taken we found earlier
115 std::cout << "Time taken: " << time << " seconds" << std::endl;
116
117 return 0;
118}
static void test()
Self-tests the sieve function for major inconsistencies.
int main()
Main function.
for assert
void sieve(std::vector< bool > *vec)
Performs the sieve.
void print_primes(std::vector< bool > const &primes)
Prints all the indexes of true values in the passed std::vector.
std::vector< int > primes(size_t max)