Project Euler Problem 10. Sum of all primes < 2mil
One of the fastest way to find primes is with a Sieve, which works like this:


(image courtesy of linked Wikipedia article)

All you have to do is create an array with 2 million elements:

#define MAX 2000000

// ...

bool* getSieve()
{
    bool isPrimeArray[] = new bool[MAX + 1];


Then you perform the sieve to it:

    for (int i = 2; i &lt;= n; i++) {
        isPrimeArray[i] = true;
    }
    for (int i = 2; i * i &lt;= n; i++) {
        if (isPrimeArray[i]) {
            for (int j = i; i * j &lt;= n; j++) {
                isPrimeArray[i * j] = false;
            }
        }
    }


And sum it:

    int index = 0;
    long result = 0;
    for (boolean isPrime : isPrimeArray) {
        if (isPrime) {
            result += index;
        }
        index++;
    }
    return result;


Result:

#include &lt;iostream&gt;

#define MAX 2000000

bool* getSieve()
{
    bool isPrimeArray[] = new bool[MAX + 1];
    for (int i = 2; i &lt;= n; i++) {
        isPrimeArray[i] = true;
    }
    for (int i = 2; i * i &lt;= n; i++) {
        if (isPrimeArray[i]) {
            for (int j = i; i * j &lt;= n; j++) {
                isPrimeArray[i * j] = false;
            }
        }
    }
}

int sumAllPrimes()
{
    bool* isPrimeArray = getSieve();
    int index = 0;
    long result = 0;
    for (boolean isPrime : isPrimeArray) {
        if (isPrime) {
            result += index;
        }
        index++;
    }
    return result;
}

int main()
{
    cout &lt;&lt; sumAllPrimes();
}