Project Euler Problem 10: Summation of primes

I have tried a few attempts on this problem working to make it more efficient each time. When I run it locally with node js it gives me the correct answer in less than a second, but when I try to run it on freeCodeCamp it tells me I do not get the right answer for primeSummation(2000000). I have run into this issue before when my code isn’t “efficient enough” for CodeCamp, but in this case I’m really struggling how to make it more efficient in order to pass all the tests on the freeCodeCamp website itself. Suggestions?!

Your code so far


function sieve(n){
    let prime = [];
    for(let i = 1; i < n + 1; i++){
        prime.push(true);
    }
    prime[0]=false; // 0 not prime
    prime[1]=false; // 1 not prime
    let p = 2;
    while(p*p<=n){
        if(prime[p] == true){
            for(let i = 2*p; i<=n; i += p){
                prime[i] = false;
            }
        }
        p += 1;
    }
    return prime;
}

function primeSummation(n){
    let prime = sieve(n);
    let sum = 0;
    for (let i=0; i<prime.length; i++){
        if(prime[i]==true){
            sum = sum + i;
        }
    }
    return sum;
}
console.log(primeSummation(2000000))

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36.

Link to the challenge:

I only have an idea for the first part in sieve(). For some strange reasons not the full loop is executed with n=2000000

You can replace it with:
var prime = Array(n).fill(true);

But even then the result is not correct, so you have to find another solution for the following while and for-loop

I coded my sieve data structure a bit differently, as here:

function primesLessThanNum(max) {
  let numbers = Array(max-1);
  for (let i=2; i <= max; i++) { numbers[i-2] = i; }
    
  let primes = [];
  while (numbers.length > 0) {
    let nextPrime = numbers[0];
    numbers = numbers.filter(n => { return n % nextPrime != 0; });

    primes.push(nextPrime);    
  }
    
  return primes;
}

and encounter the same problem.

It appears to be time- or CPU-based rather than memory-based, as the wrong values that I get vary from run to run. I have narrowed it down to (almost) always running successfully up to 40,000, but failing consistently at 50,000.

What is particularly mysterious is that the function is returning an incomplete array primes on failure, rather than simply aborting. That suggests that a try-catch might be possible that attempts restart on the failed iteration.