Sum All Odd Fibonacci Numbers might be broken

Sum All Odd Fibonacci Numbers might be broken
0

#1

So the code below works, I’ve tested every number the test script throws at it and it provides the correct answer every time. I believe the test code for this challenge may be in error as it claims my code doesn’t pass any tests.

Your code so far

  var fiblist = [];
  function sumFibs(limit, num) {
    // if (limit < 2) { return 1; }
    if (num >= limit) { return addOdds(); }
    if (num == undefined) { num = 1; fiblist.push(0); }
    fiblist.unshift(num);
    return sumFibs(limit, (fiblist[0]+fiblist[1]));
  }

  function addOdds() {
    var answer = 0;
    for(var f in fiblist) {
      var fib = fiblist[f];
      if(fib % 2 != 0) {
        answer += fib;
      }
    }
    return answer;
  }

sumFibs(1000);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0.

Link to the challenge:


#2

Individually, your code may pass the test cases, but the FCC tests are ran consecutively, so that global variable declaration you are using:

var fiblist = [];

does not get reset on each subsequent test. Basically, fiblist will have whatever it at the end of the previous test, which will result in the wrong answers the tests expect. You will have to rethink your solution to work without using the global variable.


#4

Thank you for pointing that out. I finally have something that passed. It doesn’t feel very elegant, but it’s recursive, so I guess that’s something.

function sumFibs(limit, n, m) {
  if (n == undefined) { return 2 + sumFibs(limit, 1, 1); }
  var x = 0;
  var temp = n;
  n = m;
  m += temp;
  console.log("n: " + n);
  console.log("m: " + m);
  if(m > limit) { return 0; }
  if(m == limit) { return m; }
  if(m % 2 != 0) { x = m; }
  console.log("x: " + x);
  return x + sumFibs(limit, n, m);
}