From a7fb4daffccbf7576674e7755675d6069148ad31 Mon Sep 17 00:00:00 2001 From: pikatech Date: Mon, 22 May 2017 20:57:36 +0200 Subject: [PATCH] Short C++ solution thanks to Bignum library support. --- 10/euler10.cpp | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 10/euler10.cpp diff --git a/10/euler10.cpp b/10/euler10.cpp new file mode 100644 index 0000000..5d9f076 --- /dev/null +++ b/10/euler10.cpp @@ -0,0 +1,48 @@ +// This solution needs the GNU MP Bignum library +// g++ euler10.cpp -o euler10 -lgmpxx -lgmp + +#include +#include +#include +#include + +void sieve(std::vector& primes, int const limit) { + if (limit < 2) { + return; + } else if (limit < 3) { + primes.push_back(2); + return; + } + primes.push_back(2); + primes.push_back(3); + + for (int num = 5; num <= limit; num += 2) { + int sqrtnum = (int) std::sqrt(num); + bool isPrime = true; + for (auto primeIt = ++primes.begin(); primeIt != primes.end() && *primeIt <= sqrtnum; ++primeIt) { + if (num % *primeIt == 0) { + isPrime = false; + break; + } + } + if (isPrime) { + primes.push_back(num); + } + } +} + +int main(void) { + constexpr int limit = 2000000; + constexpr int PRIMELIMIT = limit - 1; + std::vector primes; + sieve(primes, PRIMELIMIT); + + mpz_class sum = 0; + + for (auto primeIt = primes.begin(); primeIt != primes.end(); ++primeIt) { + sum += *primeIt; + } + + std::cout << sum << std::endl; + return EXIT_SUCCESS; +}