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
}
sumPrimes(10);
console.log(sumPrimes(1500))
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
Challenge: Intermediate Algorithm Scripting - Sum All Primes
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!