Sum All Odd Fibonacci Numbers - my seemingly correct solution isn't being accepted

Sum All Odd Fibonacci Numbers - my seemingly correct solution isn't being accepted
0

#1

I am very, very confused.

Here is my code, it’s may not be the prettiest because I was doing it recursively without looking it up so it’s not as concise as it could be:


var arr = [];
function sumFibs(num) {
  //create array of Fibonacci numbers
  fib(0, 1, num);
  //add 1 at the beginning and remove the last number (it's above num)
  arr.pop();
  arr.unshift(1);
  //get the odd numbers
  results = [];
  results = arr.filter(function(element) {
    return element % 2 == 1;
  });
  //sum the odd numbers
  var sum = 0;
  for(var i = 0; i < results.length; i++) {
    sum += results[i];
  }

  //return 60696 === sum; //true
  return sum;
}

function fib(num1, num2, stopNum) {
  sum = num1 + num2;
  arr.push(sum);
  while(sum <= stopNum) { //last number will need to be taken out
    return fib(num2, sum, stopNum);
  }
}

sumFibs(75024);

sumFibs(75024) returns 60696 - which looks a lot like the correct answer of 60696. As you can see in my code I have commented out sum === 60696, which returns true. But when I return sum the only requirement I fulfill is that “sumFibs(1) should return a number”, everything else is wrong even though it really really looks like it is returning the correct results. What stupid, dumb thing am I missing?


#2

Here’s a picture to better explain my problem: https://imgur.com/a/zRo29


#3

The globally declare arr variable is the main culprit. The FCC tests use your code to run all of their tests consecutively. Because arr is global, it starts each test after the first with the contents of the previous test. So, after the first test sumFibs(1), arr is [1,1], so when sumFibs(1000) is ran, arr is already [1,1], and it will return 1787 instead of 1785. This continues throughout the remaining tests.

Try making arr local to the sumFibs function. If you do that, you will still need to make another change because your fib function currently relies on arr being global.


#4

Well that did fix it! Thank you! But I have to say I don’t understand why it printed out the correct result in the black box.

Edit: I think I get it. The result in the black box is the result of it being run once, but it’s grading me on consecutive runs and all is well with the universe because 60696 does indeed still equal 60696.