Search code examples
javascriptmathsumfibonacci

Fibonacci Numbers - Add odd numbers only - Javascript


So I am trying to develop a formula that will sum all odd Fibonacci numbers up to and including a given number.

For example:

  • Given number is 4. Then result should be 5 (Odd Fibonacci numbers being 1, 1, 3).

Currently this is my code:

function sumFibs(num) {
  var sum = 0;
  for(i=0,j=1,k=0; k<=num;i=j,j=x,k++) {
    x = i + j;
    if (x%2 !== 0) {
      sum +=x;
      if (sum >= sum) {
        break;
      }
    }
  }
  return sum;
}
sumFibs(4);

Clearly the code doesn't work. If I remove the (if sum >= sum) break statement it creates an infinite loop. I have taken the for loop from another post here where a formula was given to create a Fibonacci sequence, but I am having difficulty with what to do after that number is generated, how do I add it. My way of trying to do this is by checking if the modulus is not 0 (which indicates it is an odd number).

Thanks for your help.


Solution

  • your code is a bit confusing with the variables names and declaration (always try to declare using var). here's a function that gets what you need

    function sumFibs(num) {
      var fib0 = 0;
      var fib1 = 1;
      var fib = 1;
      var sum = fib0;
      while ( fib <= num){
        if (fib % 2) {
            sum += fib1;
        }
        fib = fib0 + fib1;
        fib1 += fib0;
        fib0 = fib1 - fib0;
      }
    
      return sum;
    }