Problem 2: Even Fibonacci Numbers

Hello ,

I’ve solved this problem like this

function fibonacci(n) {
  return (n <= 1) ? 1 : (fibonacci(n - 1) + fibonacci(n - 2));
}

function fiboEvenSum(number) {
  let fibonacciSequence = [];
  let sum;

  for (let i = 1; i <= (number+1) ; i++) {
    if (fibonacci(i) % 2 === 0) fibonacciSequence.push(fibonacci(i));
  }

  sum = fibonacciSequence.reduce((acc, val) => acc + val);
  return sum;
}

It gives me the right answer when I run it on node
But when I run it on “Run the test” … it doesn’t pass the test
what is my problem ?

Hey,

Fib series is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, …

Do you see this issue with your code now? hint- your fibonacci(0) returns 1.

Thank you
I have fixed something but I miss the other point

function fibonacci(n) {
  return (n === 0) ? 0 : 
  (n === 1) ? 1 : (fibonacci(n - 1) + fibonacci(n - 2));
}

function fiboEvenSum(number) {
  let sum = 0, fibo;
  for (var i = 1; i <= number+3; i++) {
    fibo = fibonacci(i);
    // if (fibo >= 4000000) {break};
    if (fibo % 2 === 0) {sum += fibo};
  }
  return sum;
}

I’ve fixed the fibonacci(0) mistake
but I don’t get the other issue

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

Your code does get the correct result. The problem is that it does not do it as efficiently as is possible. The test for fiboEvenSum(43) appears to think you have an infinite loop (even though you don’t) and tests stop prematurely before completing. See if you can find a more efficient algorithm for your solution.

1 Like

Thank you randelldawson