Project Euler Problem #10 I've read other solutions about solving the 10th problem for Project Euler (finding the sum of all prime numbers under 2,000,000) but I wanted to try it on my own using the Sieve of Eratosthenes method. It runs quickly and it seems to work for all of my test increments (under 10, first 1000 primes) but it doesn't seem to work for the full 2,000,000 range. I was wondering if anyone could help point out the problem in my code. I know it's not the prettiest/most efficient code, so sorry.

#include &lt;iostream&gt;

using namespace std;

int main(int argc, char const *argv[])
{
    // upper limit &amp; sum
    int sum = 0;
    int upLimit = 2000000;

    // array of isPrime check for integers
    bool isPrime[upLimit+1];

    // initialize
    for (int i=2; i &lt;= upLimit; i++) {
        isPrime[i] = true;
    }

    for (int i=2; i&lt;=upLimit; i++) {
        if (isPrime[i]) {
            // add to sum
            sum += i;

            // mark all multiples
            int j = i;
            while (j &lt;= upLimit) {
                isPrime[j] = false;
                j += i;
            }
        }
    }
    cout &lt;&lt; sum &lt;&lt; endl;
}
You need to check for overflow before adding.

for (int i=2; i&lt;=upLimit; i++) {
    if (isPrime[i]) {
        // Check for overflow
        if (std::numeric_limits&lt;decltype(sum)&gt;::max() - sum &lt;= i) {
            std::cerr &lt;&lt; "Overflow" &lt;&lt; std::endl;
            return 1;
        }

        // add to sum
        sum += i;
        …


As int is only guaranteed to hold values up to 32767, you'll find that you should use a long long for sum.