Sum All Odd Fibonacci Numbers. Test don't work with 4000000

Tell us what’s happening:

I wrote a working solution. But it somehow does not pass the test for 4000000. Although on repl it works without problems.
For some reason, the function that generates an array of Fibonacci numbers stops before the terminal condition is satisfied

Your code so far


function sumFibs(num) {
  function fib(n) {
    return n <= 1 ? n : fib(n - 1) + fib(n - 2);
  };
  const fibArrMake = (n) => {
    let result = [];
    for (let i = 0; ; i++) {
      if (fib(i) > n) {
        break;
      }
      result.push(fib(i));
    }
    return result;
  };
  const fibArr = fibArrMake(num);
  const filtered = fibArr.filter(el => el % 2);
  const sum = filtered.reduce((acc, el) => acc + el, 0);
  return sum;
}

sumFibs(4);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers

FCC uses infinite loop protection to prevent campers from having to deal with their browsers crashing when they write an infinite loop or infinite recursion. This is timer-based, so it may just be that your solution is slow enough that it triggers the loop protection.

I thought you could do //no-protect or something along those lines.

I haven’t verified whether that is how it works in the new curriculum.

@ArielLeslie is correct, we use the loop-protect package.

There is a limit of 100 ms, as can be seen here

We could maybe push this up a little.

The // noprotect does not seem to be working though…

So, recursioin it’s not good((

Recursion gives you a bad performance without an optimization but results more comprehensible code.
You can rewrite the code to use iteration. In case of fibonacci computation, both iterative or recursive solution will be easy to understand.

1 Like

It would be great to increase the callstack, this is not the first time I encounter the fact that the work of functions stops before it reaches the end.

I think the real lesson from this type of challenge is that you must create efficient algorithms.