From 9076d947b4a93b3b803f2ae59a79e0e297b135c7 Mon Sep 17 00:00:00 2001 From: Sandipan Mohanty <s.mohanty@fz-juelich.de> Date: Fri, 17 May 2024 10:30:28 +0200 Subject: [PATCH] Update chapter_08 examples --- chapter_08/examples/eratostenes_sieve.cc | 46 ++++++++++++++++++++++++ chapter_08/examples/hello_m.cc | 4 +-- 2 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 chapter_08/examples/eratostenes_sieve.cc diff --git a/chapter_08/examples/eratostenes_sieve.cc b/chapter_08/examples/eratostenes_sieve.cc new file mode 100644 index 0000000..41f9d74 --- /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 f743015..2c983dc 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"); } -- GitLab