Sum All Primes - Where is a problem?

Hi guys, I struggle a bit through intermediate algorithm, so I was happy that I did this challenge but it does not want to let me pass, despite the expected outcome.

function sumPrimes(num) {
  let arr = [];
  let newArr = [];
  for(let i=1; i<num+1; i++){
    arr.push(i);
  }
  for(let i=1; i<arr.length; i++){
    let s = 0;
    for(let y=1; y<arr[i]; y++){
      if(arr[i] % y === 0){
        s++;
      }
    }
    if(s < 2){
      newArr.push(arr[i]);
    }
  }
  return newArr.reduce((d, e) => d + e);
}

sumPrimes(10) // 17 - ok
sumPrimes(977) // 73156 - failed

sumPrimes(10) should return 17.
sumPrimes(977) should return 73156.

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

Posted here it gives issues on the length. You need a more efficient code. If you will be able to make it run on the Tutor you will be able to pass FCC challenge almost for sure

Thank you, I thought than performance could be issue here.

I had quite a cheesy solution to this but it works for the FCC problems and I solved it quite quickly. I’m not sure I’m the best person to help you since I don’t want to mess you up if you’re on track for the better solution (which obviously I don’t know, haha.) But if you’re interested, my suggestion is… Maybe you could do something to the first 10 prime numbers? Hopefully you’ve solved it by now, though. :wink:

A few hints any one of which could increase performance. You probably couldn’t use all of them together but you might experiment with one or more.

A number that is not divisible by any lesser primes would be prime too. Your newArr is a list of all primes so far found which would be all lesser primes.

You put your found primes into an array but then only use it by reducing it for a total. Why not just keep a running sum and skip the whole reduce step? sum+=i;

When looking for factors (testing potential factors) of a number you don’t have to look at every number less than itself. Using 36 as an example below you can see that you don’t need to test 18 as a factor because you have already tested 2 (2,18). See anything unique about that midpoint? As your number gets larger this could save you a lot of testing.

1 36
2 18
3 12
4 9
6 6
9 4
12 3
18 2
36 1

Some things I see specific to your algorithm…
You are using a for…loop from 1 to num to make an array 1 to num so you can get at those numbers with another for loop using arr[i]. Why not just loop 1 to num and use i? Only one loop and you don’t store all those numbers in memory.

Your inner for…loop continues even after you have found the number to be divisible by y. With some careful thought you might be able to break out of that loop when that occurs. You would probably need to handle the special cases of 1 (which it looks that you have done) and maybe 2 and / or 3.

Good luck. This is a difficult challenge.

where you able to solve this at the end?