Sum All Odd Fibonacci Numbers, infinite loop?

Sum All Odd Fibonacci Numbers, infinite loop?
0

#1

Tell us what’s happening:
stuck there, is it a infinite loop? But I have a condition to break the while loop so I don’t think it
is an infinite loop.

Your code so far

function sumFibs(num) {
  
  function fib(n){
    if(n<=1){
      return 1;
    }
    return fib(n-1) + fib(n-2);
  }
  

  var total = 0;
  var i = 0;
  while (1 == 1) {
    if(fib(i) < num ){
       if(fib(i) % 2 !== 0){
        total += fib(i);
        i += 1;
       }
    }else{
      break;
    }
  }
  return total;
}

sumFibs(4);

Your browser information:

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

Link to the challenge:


#2

i doesn’t increment when fib(i) % 2 is even, so you get stuck in a loop.

You may also want to store fib(i) in a variable in the while loop, so that there’s only one fib computation per loop instead of three.


#3
while (1 == 1) {
    if(fib(i) < num ){

Just because it’s going to bug me if I don’t say something, you really don’t want a while(true) (or a variant thereof).

Why not just make your loop while(fib(i) < num?

I’m not saying that this is necessarily the way you want to solve the problem, but I wanted to addresss the fundamental misunderstanding of how to use a while loop.


#4

Thanks, that is good catch


#5

Thank you so much for the suggestion