Sum All Odd Fibonacci Numbers Challenge

Sum All Odd Fibonacci Numbers Challenge
0

#1

Hi, I can’t seem to pass the second last test in any way, here’s what I have at the moment for the challenge:

function sumFibs(num) {
  var sum = 0;
  var fib = 0;

  while (sum <= num) {
    var currentFib = fibo(fib);
    if (currentFib %2 === 1) {
      sum += currentFib;
    }
    fib++;
  }
  return sum;
}

function fibo(n) {
  if (n <= 1) return 1;
  return fibo(n - 1) + fibo(n - 2);
}

console.log(sumFibs(10));
console.log(sumFibs(75024));
console.log(sumFibs(75025));

Has it got to do with my logic or something else? Any help would be appreciated! Thanks!

Link to challenge: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers/


#2

In the fibo function you should return n when the value of n is less than or equal to 1. Or, you can return 1 when n is equal to 1 and you can return 0 when n is equal to 0.


function fibo(n) {
  if (n <= 1) return n;
  return fibo(n - 1) + fibo(n - 2);
}

OR

function fibo(n) {
 if(n == 0) return 0;
  else if (n == 1) return 1;
  else return fibo(n - 1) + fibo(n - 2);
}

#3

Hmm, I tried that but doesn’t seem to be the problem. Any other ideas?


#4

Can you repost your latest code?


#5
function sumFibs(num) {
  var sum = 0;
  var fib = 0;

  while (sum <= num) {
    var currentFib = fibo(fib);
    if (currentFib %2 === 1) {
      sum += currentFib;
    }
    fib++;
  }
  return sum;
}

function fibo(n) {
  if (n <= 1) return n;
  return fibo(n - 1) + fibo(n - 2);
}

//console.log(fibo(2));
console.log(sumFibs(10));
console.log(sumFibs(75024));

I’ve just changed what alvee suggested to just return n, still failing the second last test “sumFibs(75024) should return 60696.”


#6

Update: That was because I missed an important detail
Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num.

Fixed code:

function sumFibs(num) {
  var sum = 0;
  var fib = 0;

  while (sum <= num) {
    var currentFib = fibo(fib);
    if (currentFib %2 === 1 && currentFib <= num) {
      sum += currentFib;
    }
    fib++;
  }
  return sum;
}

function fibo(n) {
  if (n <= 1) return n;
  return fibo(n - 1) + fibo(n - 2);
}

console.log(sumFibs(10));