Sum All Primes problem

Sum All Primes problem
0

#1

Tell us what’s happening:
For large numbers my for loop for checking if the number is prime stops on the way for a reason not known to me.

Your code so far


function sumPrimes(num) {
  var numList = [];
  var primeSum = 0;
  var primeList = [];
  for (let i = 2; i <= num; i++) {
    numList.push(i);
    
  }
 // console.log("numList is " + numList);
  function isItPrime(nr) {
     console.log("running isItPrime for " + nr);
     if (nr==2) {
       console.log(nr + " is prime");
          return true;
     } else {
     
      for (let j=2; j<nr; j++) {
        if (nr%j===0) {
          console.log(nr + " is not prime");
          return false;
          }
        }
        console.log(nr + " is prime");
          return true;
      }
    }
    //console.log("isItPrime(" + num + ") returns " + isItPrime(num));
    for (let k = 0; k<numList.length; k++) {
      if (isItPrime(numList[k])===true) {
        console.log ("in the loop we got "+ numList[k]);
        primeList.push(numList[k]);
      }
    }
    console.log("primeList is " + primeList);
    for (let m = 0;m < primeList.length; m++) {
      primeSum+= primeList[m];
    }
    console.log("the sum is " + primeSum);
    return primeSum;
}

sumPrimes(18);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes


#2

I’m pretty sure it’s because you are hitting the limit for the tests timeout. I’m pretty sure if you let it run on other editors like jsfiddle that you’d be able to get the result, but for FCC, they have a timer that autofails you if you reach it. You’ll need to try and figure out a more efficient algorithm.


#3

The tests timeout limit being the number of if statement or what does it mean exactly?


#4

Amount of time, usually on the order of hundreds of milliseconds I think.


#5

I solved it by commenting out the console.logs. Is the method I used really so inefficient?


#6

There are few things to cut down on the time.

For example, you can start the for loop at 3 and skip every even number. You can also not check beyond the sqrt of the original number.


#7

I found that too – console.log() is, apparently, computationally intensive. Removing them was the only way I could get the larger tests to pass. And for the record, DON’T test it with a number in the millions, it’s practically an infinite loop at that point. :wink:


#8

Haha, I noticed all hell breaks loose then.