diff --git a/chapter_08/examples/eratostenes_sieve.cc b/chapter_08/examples/eratostenes_sieve.cc new file mode 100644 index 0000000000000000000000000000000000000000..41f9d74614a24885d26cd77c5271cc819827627e --- /dev/null +++ b/chapter_08/examples/eratostenes_sieve.cc @@ -0,0 +1,46 @@ +#include <chrono> +#include <ranges> +#include <algorithm> +#include <iostream> +#include <vector> +#include <span> +#include <cxxopts.hpp> + +namespace sr = std::ranges; + +template <class T> +void assign_each_nth(std::span<T> R, size_t n, T v) +{ + for (auto i = 0UL; i < R.size(); i += n) + R[i] = v; +} + +auto main(int argc, char* argv[]) -> int +{ + std::cout << "Erastothene Sieve...\n"; + using namespace std; + using namespace std::chrono; + auto N = 100UL; + vector<int> candidate(N + 1, 1); + candidate[0] = candidate[1] = 0; + auto proc = std::span(candidate); + auto t0 = steady_clock::now(); + for (size_t i = 2; i <= (N / 2); ++i) { + if (candidate[i]) { + assign_each_nth(proc.subspan(2 * i), i, 0); + } + } + auto t1 = steady_clock::now(); + std::cout << "Calculating primes up to " << N << " took " + << duration<double>(t1 - t0)<< "\n"; + + std::cout << "Write primes ? (y/n): "; + char ch; + std::cin >> ch; + if (ch == 'y') + for (size_t i = 0; i < N; ++i) + if (candidate[i]) + std::cout << i << "\n"; + std::cout << "Prime count = " + << sr::count(candidate, 1) << "\n"; +} diff --git a/chapter_08/examples/hello_m.cc b/chapter_08/examples/hello_m.cc index f743015337ce7b049038e5ba97b0fca1e08ae90d..2c983dc987711dbf0067ecdb86cf2c15e8a74331 100644 --- a/chapter_08/examples/hello_m.cc +++ b/chapter_08/examples/hello_m.cc @@ -1,7 +1,7 @@ -import <iostream>; +import <print>; auto main() -> int { - std::cout << "Hello, world!\n"; + std::print("Hello, world!\n"); }