Potential infinite loop: Intermediate Algorithm Scripting - Sum All Primes

Tell us what’s happening:
The code below is my solution. It works well enough for the scope of the tests listed, but when I tried console.log(sumPrimes(1700)), it returned the result with an added warning of a potential infinite loop on line 3. Is this due to there just being too many iterations happening with a number that large, or is there something I should have done differently in the code?

Your code so far

function sumPrimes(num) {
  let result = 0
  for (let i = 2; i <= num; i++) {
    let isPrime = true
    for (let j = 2; j < i; j++) {
      if (i % j == 0)
        isPrime = false
    if (isPrime === true)
      result += i
  return result



Your browser information:

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

Challenge: Intermediate Algorithm Scripting - Sum All Primes

Link to the challenge:


Also yes

You are doing much more work than you need to in order to solve this problem.

Stuff like this

There is only one even prime, you are checking 2x as many numbers as you need

You don’t need to check all the way up to i, what’s the biggest possible unique divisor? You can cut out many iterations here.

Why keep looping after you know this? You can cut out a ton of iterations here too.

If you only check odd numbers, you can start after 2 here

1 Like

Thank you! This is exactly what I needed. I’ll try to be more mindful of how I can cut down on loop iterations in the future. I altered the code declaring the inner loop to utilize Math.sqrt and that alone helped exponentially. I’ll continue to tinker with it using your other suggestions. Much appreciated and happy holidays to you!

Happy to help! Cutting out extra work can be tricky. Getting working code is always priority #1, and you got that, so good work!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.