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.
Your code so far
//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))
Your browser information:
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.
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.
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.