From 342dca927f1758e0cf20572297c78fca8422b939 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 20 Aug 2022 20:19:36 +0200 Subject: [PATCH] =?UTF-8?q?5kyu(cpp):=20add=20=E2=80=9E(Ready=20for)=20Pri?= =?UTF-8?q?me=20Time=E2=80=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- 5kyu/prime_time/solution.cpp | 63 ++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 64 insertions(+) create mode 100644 5kyu/prime_time/solution.cpp diff --git a/5kyu/prime_time/solution.cpp b/5kyu/prime_time/solution.cpp new file mode 100644 index 0000000..47d95c6 --- /dev/null +++ b/5kyu/prime_time/solution.cpp @@ -0,0 +1,63 @@ +#include +#include + +namespace { + +inline std::size_t index(unsigned p) { return p - 2; } +inline bool is_prime(const std::vector &primes, unsigned p) { + return primes[index(p)]; +} + +void discard_multiples(std::vector &primes, unsigned p) { + for (auto k = 2; index(p * k) < primes.size(); k++) { + primes[index(p * k)] = false; + } +} + +void discard_even(std::vector &primes) { discard_multiples(primes, 2); } + +std::vector construct_primes(const std::vector &primes) { + std::vector result; + + for (auto p = 0u; p < primes.size(); p++) { + if (primes[p]) { + result.push_back(p + 2); + } + } + + return result; +} + +} // namespace + +// Generate an array containing every prime number between 0 and the num +// specified (inclusive) +std::vector prime(unsigned n) { + if (n < 2) { + return {}; + } + + std::vector primes(n - 1, true); + discard_even(primes); + + for (auto p = 3u; p <= n; p += 2) { + if (!is_prime(primes, p)) { + continue; + } + + discard_multiples(primes, p); + } + + return construct_primes(primes); +} + +int main() { + assert(prime(0) == std::vector{}); + assert(prime(1) == std::vector{}); + assert(prime(2) == std::vector{2}); + assert((prime(23) == std::vector{2, 3, 5, 7, 11, 13, 17, 19, 23})); + assert( + (prime(30) == std::vector{2, 3, 5, 7, 11, 13, 17, 19, 23, 29})); + + return 0; +} diff --git a/README.md b/README.md index 413845a..3a99e57 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,7 @@ - [Greed is Good](https://www.codewars.com/kata/5270d0d18625160ada0000e4) - [solution](5kyu/greed_is_good) - [Snakes and Ladders](https://www.codewars.com/kata/587136ba2eefcb92a9000027) - [solution](5kyu/snakes_and_ladders) - [The Clockwise Spiral](https://www.codewars.com/kata/536a155256eb459b8700077e) - [solution](5kyu/the_clockwise_spiral) +- [(Ready for) Prime Time](https://www.codewars.com/kata/521ef596c106a935c0000519) - [solution](5kyu/prime_time) ### Python