Calculate the sum of all the primes below two million.
Inte så elegant lösning, transportsträcka.
#include <iostream>
#include <cmath>
template <typename T>
inline bool is_prime(T p)
{
if (p == 1)
return false;
if (p == 2)
return true;
if (!(p & 1))
return false;
for (T i = 2; i < sqrt(p) + 1; ++i)
if (!(p % i))
return false;
return true;
}
int main(int argc, char *argv[])
{
uint64_t prime_sum = 0;
for (uint64_t i = 0; i < 2000000; ++i)
if (is_prime(i))
prime_sum += i;
std::cout << "Answer is " << prime_sum << std::endl;
return 0;
}
Inga kommentarer:
Skicka en kommentar