# Sum All Primes - Infinite Loop

Tell us what’s happening:

Hi everyone, I did eventually solve this problem, perhaps rather inelegantly, with a lazy “-1” at the end. However, my initial attempt was getting caught in two infinite loops. I’m not sure why creating a test array solved the problem in the end. Any feedback would be appreciated by this beginner.

``````//flawed code
function sumPrimes(num) {
var primeArr = []
for (var i=1; i++; i<num) {
var count = 0
for (var j=1; j++; j<=i) {
if (i%j === 0) {
count++
}
} if (count>2) {
primeArr.push(i)
}
}
return primeArr;
}

sumPrimes(10)
console.log(sumPrimes(10))
``````
``````//working code
function sumPrimes(num) {
var primeArr = []
var testArr = []
const reducer = (x,y) => x+y
for (var i=0; i<=num; i++) {
testArr.push(i)
}
for (var j=0; j<=num; j++) {
var count = 0
for (var k=0; k<=num; k++) {
if (testArr[j]%testArr[k] == 0) {
count++
}
} if (count<3) {
primeArr.push(testArr[j])
}
}
return primeArr.reduce(reducer) - 1
}

sumPrimes(10)
console.log(sumPrimes(10))
``````

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

Challenge: Sum All Primes

The test array just makes roughly the same code more complicated. Your return statements are different, so I’m not sure how to compare your two codes.

1 Like

Hello. You have to divide the problem. As you have written it, it is all together in one function. First find out which number is prime. Create a function that does that specific task and if the number turns out to be prime then add it up. Greetings.

1 Like

Hi Jeremy, thanks for the response. I should have been more clear. My question is why FCC was warning me for an infinite loop on the first set of code, but not the second. As for the return, I hadn’t yet bothered to reduce the array in the first set of code. I also felt that the test array was redundant, but it seemed to get it working.

Hmm, I would have expected both to have the infinite loop warning since the complexity of both is the same.

1 Like

Yeah, I was happy to have figured out working code on my own, but also grateful to see the much more efficient code in the solutions afterwards.

Out of curiosity… Does the first code still infinite loop if you use `let` instead of `var`? I suspect hoisting of variables may be the issue here.

I’d test myself, but coding on a phone…

I am a huge fan of looking at other’s solutions after you have yours working.

For math heavy problems I totally recommend doing some Googling for approaches. Research and planning is a huge part of coding.

1 Like