Intermediate Algorithm Scripting - Sum All Odd Fibonacci Numbers

Tell us what’s happening:
I’m not really sure what I’m doing wrong with this code. If I use smaller numbers such as 4 I get the correct output. I wanted to use recursion to add up all the elements

Your code so far

function fibonacci(num) {
  let fibArr = [];
  let a = 1, b = 0, temp;

  while (num >= 0) {
    if (b % 2 !== 0) {
      fibArr.push(b);
    }
    temp = a;
    a = a + b;
    b = temp;
    num--;
  }

  
  function sumArrayRecursive(arr, index) {
    if (index === arr.length) {
      return 0;
    } else {
      return arr[index] + sumArrayRecursive(arr, index + 1)
    }
  }

  return sumArrayRecursive(fibArr, 0);
}

let r = fibonacci(1000);
console.log(r); 




 

Your browser information:

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

Challenge: Intermediate Algorithm Scripting - Sum All Odd Fibonacci Numbers

Link to the challenge:

Recursion is an slow approach here, but not too bad.

Why are you decreasing the num? I don’t think you quite understand which numbers you need to make.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.