freeCodeCamp Challenge Guide: Problem 2: Even Fibonacci Numbers

Problem 2: Even Fibonacci Numbers


Problem Explanation

  • A fibonacci sequence is a sequence where fib(n) = fib(n-1) + fib(n-2).
  • In this challenge we have to sum all the even Fibonacci values up to and including the value n:.
  • Example for fiboEvenSum(8):
    • The sequence up to and including the value 8 is:
      1, 2, 3, 5, 8

    • Sum of all even number in the above sequence is:
      2 + 8 = 10

Relevant Links


Solutions

Solution 1 (Click to Show/Hide)
const fiboEvenSum = (number) => {
  if (number <= 1) {
    return 0;
  } else {
    let evenSum = 0,
      prevFibNum = 1,
      // According to problem description our Fibonacci series starts with 1, 2
      fibNum = 2; 
    for (let i = 2; fibNum <= number; i++) {
      if (fibNum % 2 == 0) {
        evenSum += fibNum;
      }
      [prevFibNum, fibNum] = [fibNum, prevFibNum + fibNum];
    }
    return evenSum;
  }
};
1 Like