Sum All Primes Help with Test 3

Test 3 fails:

My code always fails on test 3. Oddly, when I increase the number of factors in the factors arr located in the checkPrime() function, sumPrimes(977) gets closer to the correct answer.

For example, if I add the number 11 to the factors array, the return value of sumPrimes(977) is 99k.

Your code so far


function checkPrime(num) {
  // These factors should be shared by all non-prime nums above 10
  const factors = [2, 3, 5, 7];
  // If the passed num is in factors, return true; all nums in factors should be true
  if (factors.includes(num)) {
    return true;
  // 1 is not prime, return false
  } else if(num==1) {
    return false;
  }
  // The num arg should not be divisible by any of the factors, so testPrime will only be true if num is not evenly divisible
  let testPrime = factors.every(factor => (num / factor) != Math.floor(num/factor));
  return testPrime;
}

function sumPrimes(num) {
  // Creates an array of nums from 0 up to and including the num argument
  const nums = [...Array(num+1).keys()];
  // fNums should only contain prime numbers
  const fNums = nums.filter(x => checkPrime(x));
  return fNums.reduce((total, sum) => total+sum);
}

console.log(sumPrimes(10)); // returns 17, passing the first two tests
console.log(sumPrimes(977)); // returns 108,789 when it should be 73,156

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.1 Safari/605.1.15.

Link to the challenge:

I might rethink your checkPrimes function. Two glaring off-the-cuff examples where it will fail? 121 and 169 (11 and 13 squared, respectively).

By creating a factors array, you’re setting the first four primes. Instead, what would be a more robust and complete solution (though perhaps brute-force) might be to implement a Sieve of Eratosthenes. Take a look at the wikipedia article on the Sieve, its actually a fun read.

1 Like

I got the code the return true for those cases, 121 169, oddly enough it was having issues somewhere in the hundreds range despite having all the primes from 0-100.
I got test 3 to pass last night by increasing the factors arr to include some more factors. I’ll look into your suggestion though as my factors arr is pretty long now and the code doesn’t look great.