1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-23 08:53:48 +01:00

5kyu(cpp): add „(Ready for) Prime Time“

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-08-20 20:19:36 +02:00
parent 4a94236571
commit 342dca927f
Signed by: mfocko
GPG key ID: 7C47D46246790496
2 changed files with 64 additions and 0 deletions

View file

@ -0,0 +1,63 @@
#include <cassert>
#include <vector>
namespace {
inline std::size_t index(unsigned p) { return p - 2; }
inline bool is_prime(const std::vector<bool> &primes, unsigned p) {
return primes[index(p)];
}
void discard_multiples(std::vector<bool> &primes, unsigned p) {
for (auto k = 2; index(p * k) < primes.size(); k++) {
primes[index(p * k)] = false;
}
}
void discard_even(std::vector<bool> &primes) { discard_multiples(primes, 2); }
std::vector<unsigned> construct_primes(const std::vector<bool> &primes) {
std::vector<unsigned> 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<unsigned> prime(unsigned n) {
if (n < 2) {
return {};
}
std::vector<bool> 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<unsigned>{});
assert(prime(1) == std::vector<unsigned>{});
assert(prime(2) == std::vector<unsigned>{2});
assert((prime(23) == std::vector<unsigned>{2, 3, 5, 7, 11, 13, 17, 19, 23}));
assert(
(prime(30) == std::vector<unsigned>{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}));
return 0;
}

View file

@ -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