Problem 2: Even Fibonacci Numbers Output Not satisfying

Tell us what’s happening:
This code seems right. Tell me what should be the output of fiboEvenSum(2) , fiboEvenSum(5)?

Your code so far


function fiboEvenSum(n) {
  // You can do it!
  // n is the term number of fibonacci where 3 is f1
  // we are creating the variables evenFibonacci(ef_i) that are 3*i == original fibonacci
  var ef0 = 2;
  var ef1 = 8;
  var sum = 0;
  if( n > 0 )
    sum += ef0;
  if( n > 3 )
    sum += ef1;
  for(var i=2; 3*i <= n ;i++)
  {
    var ef2=4*ef1+ef0;
    sum+=ef2;
    ef0 = ef1;
    ef1 = ef2;
  }
  return sum;
}

fiboEvenSum(10);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/project-euler/problem-2-even-fibonacci-numbers

2 and 10. Was going to say depends on start value (0 or 1), but it tells you the sequence in the description.

Btw can you explain what you’re thinking is with your code, what algorithm you have used here? Eg why 8, why 3 * and 4 *?

In my code also fiboEvenSum(2)=2, fiboEvenSum(5)=10. If that is the desired output then I do not see anything wrong with my code but it is not getting accepted.

I will explain my algorithm here,
if 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, … is the Fibonacci series, every third number even numbers are at gap of 3.
So even fibonacci series is 0, 2, 8, 34, 144, 610, 2584…

Fn = Fn-1 + Fn-2 [Expanding both terms]
= Fn-2 + Fn-3 + Fn-3 + Fn-4
= Fn-2 + 2Fn-3 + Fn-4 [Expending first term]
= Fn-3 + Fn-4 + 2Fn-3 + Fn-4
= 3Fn-3 + 2Fn-4 [Expending one Fn-4]
= 3Fn-3 + Fn-4 + Fn-5 + Fn-6 [Combing Fn-4 and Fn-5]
= 4Fn-3 + Fn-6

Since every third Fibonacci Number is even, So if Fn is
even then Fn-3 is even and Fn-6 is also even. Let Fn be
xth even element and mark it as EFx.
If Fn is EFx, then Fn-3 is previous even number i.e. EFx-1
and Fn-6 is previous of EFx-1 i.e. EFx-2
So
Fn = 4Fn-3 + Fn-6
which means,
EFx = 4EFx-1 + EFx-2

So the correspondence of F_(3i) = EF_i. Thus 3*i.

So I am generating even fibonacci EF_i and adding them until F_(n)=F_(3i) gets satisfied.

If your algorithm passes at home and not in a test runner and you suspect the output :

  • format of the output might be wrong (type for ex)
  • you are exceeding the On time factor ie your algorithm times out
  • or your code is wrong . I would restart and do cleaner code.

This is what the online judge is telling.

Your function is not returning the correct result using our tests values.