Project Euler Problem 10. Sum of all primes < 2mil I'm new to coding so I can't create complex code yet. I do as much as I can with fors and ifs, since while I know a bit about arrays and other topics, I am not familiar enough with them to apply them on my own. This code works, but if I tell it to go to 2 million in main the program never finishes; 200,000 took about a minute, while 20,000 took a few seconds.

I get that this code is unoptimized and does too many unnecessary checks and calculations. Is there a way to optimize the program with just loops and conditions?

#include&lt;iostream&gt;
int nopf(int k){
    int sn=0,b;
    for(b=2;b&lt;k;b++){
        if(k%b==0)sn++;
    }
    return sn;
}

main(){
    int i,s=0;
    for(i=2;i&lt;200000;i++){
        if(nopf(i)==0)s+=i;
    }

    cout&lt;&lt;s;

}


NB: nopf is a function to check if a number is prime or not.
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();
}