Sum All Odd Fibonacci Numbers-with one failed

Tell us what’s happening:
sumFibs(4000000) when num is equal to 4000000 .The test fail.

Your code so far


function sumFibs(num) {
  let sum = 0;
  function fib(e){// 1,1,2,3,5,8,13,21,34	
    if(e==0||e==1){
      return 1;
    }else{
      return fib(e-1) + fib(e-2);
    }

  };
  for(let i=0;fib(i)<=num;i++){	
    if((fib(i)+1)%2 == 0){
      sum+=fib(i);
    }					
  }
  return sum;			
}
sumFibs(4000000);

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.99 Safari/537.36.

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

I think you have misunderstood the problem presented here. They want you to add all the numbers up to the given num, but your for loop stops well short of that (because it stops when the sum reaches the given num).

I cut the code and put it in a blank html file and run it . it shows the right answer.confused

What answer do you get for 400000?

It’ll be timing out, you’re computing extremely large numbers using a brute force recursive method. Using an algorithm that doesn’t rely on that recursive function, or rewriting the recursive function to not be recursive should make the test pass.

1 Like

hi, can you please elaborate on what you said? The code is so much cleaner than what I wrote but it’s somehow not good so I’d like to understand it to avoid it if I can.

at a certain level, programmers forget how to speak english

It’s recursive, which is very neat and looks extremely clean, and is how you would define it mathematically. But that means it’s really slow and uses lots of memory.

It is also brute force, so it enumerates through every possible number. Doesn’t matter as much with this challenge, but in general that’s a bad idea.