Efficency of Fibs Solution

Hello,

Can anyone help me understand why I get infinite loop warning only for the last test? All other tests passed.

it happened on line 7, which is the for loop condition

my code:

function fiboEvenSum(n) {
  let fib = [1,2];
  let sum = 0;
  let current = 1;
  let next = 2;

  for(let i=1; i<n; i++){
    sum = current + next;
    fib.push(sum);
    current = next;
    next = sum;
  }

  let result = 0;
  fib.forEach(el=>{
    if(el%2===0 && el<=n){
      result+=el;
    }
  })


  return result;
}

fiboEvenSum(4000000)

Hi and welcome to the forum.

I moved your question to it’s own topic.


Dynamically growing an array like this is very inefficient and not needed in this problem. You are getting the warning with large inputs because the inefficiency is most noticeable with large inputs.

thanks for your reply, can you give me any tip what with do I replace the for loop?

The Fibonacci sequence is a great example of a problem where you need to only keep track of three values at a time.

Instead of keeping every single value, I’d just keep a running sum of the even Fibs as they are generated.