Fibonacci numbers sum

Tell us what’s happening:

Hello campers,

My code is working as expected and passes all the tests. That is great!

However, I wonder whether is there a way to fill the arr using a recursion? For now I cannot figure this out.

And I’m also interested whether is my solution good enough? :slight_smile:

Your code so far


function sumFibs(num) {
  let arr = [0, 1];
  
  let index = 0;
  while (num >= arr[index + 1] + arr[index]) {
    arr.push(arr[index + 1] + arr[index]);
    index++;
  }
  
  return arr.filter(num => num % 2).reduce((a,b) => a + b);
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0.

Link to the challenge:

It works fine, but it’s quite complicated. You’re just adding numbers up, so there is no need to use arrays or array methods: you can initialise three variables (two to track the Fibonacci sequence, one for the result) then just loop and add to make the fib sequence, adding the odd ones to the result.

Example without an array:

function sumFibs(num, prev = 0, curr = 1, total = 0) {
  // return the total once the current Fibonacci
  // number goes past the target value:
  if (curr > num) {
    return total;
  }
  // Otherwise, adjust the values:
  // ---------------------------------------------------------
  // If current Fibonacci number is odd, add
  // it to the total (otherwise total stays the same):
  if (curr % 2 !== 0) {
    total = total + curr;
  }
  // Add the current and previous values to get the next number in the sequence:
  curr = curr + prev;
  // Previous value gets set to the value curr was at before it was incremented:
  prev = curr - prev;
  // Run the function again with the new values:
  return sumFibs(num, prev, curr, total);
}

Note that a non-recursive solution is always likely to be faster

1 Like

Hello!

Thank you very much! That’s a great idea how to solve it without using an array.