Sum all odd fibonacci numbers: I sometimes get the correct answer?

Hi,

  • sumFibs(10) gets the correct answer (10) with my code

  • sumFibs(4) gets the correct answer (5) with my code.

I don’t get the correct answers for other numbers? Please can someone advise.

Your code so far


function sumFibs(num) {
let arr = [1,1]
let res = 0;
let oddTotal = 2;

 for(let total = 0; total <= num; total += oddTotal){
  let old = arr[arr.length - 2];
  let newer = arr[arr.length - 1];
res = old + newer;
 arr.push(res);
if (res % 2){
    oddTotal += res;
}
 }
 return oddTotal;
}

sumFibs(4);
   **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36

Challenge: Sum All Odd Fibonacci Numbers

Link to the challenge:

I think you’re just getting those right answers by accident.

console.log(sumFibs(14)
// 10 

That is clearly wrong. I think your loop logic is off. I’m not sure I would use a for loop here. I would want one of the other two loops. I’m not saying for is impossible, it just isn’t as obvious to me. I also don’t understand why you are storing you numbers in an array. You should be able to progress through a fib series with two variables.

1 Like

Yeah, I agree that a for loop isn’t quite a good fit here.