Sum all Primes: Page Unresponsive in Some Cases

Sum all Primes: Page Unresponsive in Some Cases
0

#1

In my code, if i enter parameter as 10, then i pass all tests. But as soon as i pass 73156, the page stops responding.

I don’t understand why this is happening, cuz all nos are passed for testing.

function sumPrimes(num) {
  var primeArr = [];
  
  for(var i = num; i > 1; i--) {
    var sqrt = Math.ceil(Math.sqrt(i));
    var numsBelow = Array.from({length:sqrt}, (v,i) => i+2);
    
    var isNotPrime = numsBelow.some(num => {
      if(i !== num){
      return i % num === 0;
      }
      return false;
    });
    console.log(i, numsBelow, isNotPrime);
    if(!isNotPrime) primeArr.push(i);
  }
  return primeArr.reduce((total, current) => total + current);
}

sumPrimes(73156);

#2

How you coded, i is 73156, 73155, 73154…, so its looping 73156 times. Thats what causing the page to lag.


#3

thnx. is there a way to make this faster


#4

There is. Somewhere in teh Google verse, you can find them. Some used a sieve algorithm or a Trial Division Test