c++ - Project Euler 10 exercise -
what sum of primes below 2000000? example of sum below 10 2+3+5+7 = 17
i wrote code, still getting wrong answers: tested numbers lower few hundreds, , has shown correct answers.
#include <iostream> #include <math.h> using namespace std; bool isprime(long n) { if (n < 2) return false; if (n == 2) return true; if (n == 3) return true; int k = 3; int z = (int)(sqrt(n) + 1); // square root n, because 1 of product must lower 6, if squared root of 36 if (n % 2 == 0) return false; while (n % k != 0) { k += 2; if (k >= z) return true; } return false; } long primesumbelow(long x) { long long total = 0; (int = 0; < x; i++) // looping times of prime appearing { if (isprime(i) == true) total += i; if (isprime(i) == false) total += 0; } cout << "fd" << endl; return total; } int main() { cout << primesumbelow(20) << endl; cout << primesumbelow(2000000) << endl; system("pause"); return 0; }
the total
counter's type correctly long long
. unfortunately function primesumbelow
returns long
so, depending on platform, correctly calculated result truncated when it's returned function.
Comments
Post a Comment