Need assistance in Sum All Odd Fibonacci Numbers


#1

Challenge Name

Sum All Odd Fibonacci Numbers has an issue.

Issue Description

So I tried the code within my console, it giving back all the correct answer, however the freecodecamp testing suite is showing that I do not have the correct answer.

These are the values I am supplying to my function, currently using the latest 
version of  visual code studios console to test them. They return the answer as 
below but for the FCC test says that the values returned are not correct.

sumFibs(4); // should return 5
sumFibs(75024); // should return 60696;
sumFibs(75025); // should return 135721;

Browser Information

User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0.

Screenshot

Your Code



let a = 0;
let b = 1;
let arr = [];

function sumFibs(num) {
    if (num == 1)
        return 1;
    if (a <= num || a == 1) {
        arr.push(a);
        b += a;
        a = b - a;
        return sumFibs(num);
    }
    return arr.filter(x => { return x % 2 !== 0; }).reduce((a, b) => { return a + b; });
}

sumFibs(1);

```<img src="//discourse-user-assets.s3.amazonaws.com/original/3X/c/5/c5c4e39b747b44b5559bed10f7d2076ff7641a77.png" width="690" height="388">

#2

Code that uses global variables generally fail, because the value in the globals are retained and carried on to the next test. See this repl:

https://repl.it/J1qE/1

You may want to revise your code so it doesn’t use global variables.


#3

If you care to give me some of your time, much appreciated :slight_smile:

a) Why does the same occur after console.log(4000000), not for the other values?

b) How do I introduce variables into the local space, for recursion? Any ideas? Without using a for loop - I wanna see if I can practice without using them


#4

Probably because the array retains the values it contains for calculating sumFibs(4000000). When you do sumFibs(5), the values from the previous call are still there, and no further pushing to the array is needed because 5 is much smaller than 40000000, so those last calls have the same value.

You could write a helper function that does the actual recursion, and call that in the sumFibs function. Then move the globals inside sumFibs.

function sumFibs(num) {
  let a = 0;
  let b = 1;
  let arr = [];

  return fib(num, a, b, arr);
}

function fib(num, a, b, arr) {
  // the old `sumFibs` body goes here, with some modifications
}