Project Euler - Problem 2 - Even Fibonacci Numbers: Coding Interview Prep (freeCodeCamp)

Problem 2: Even Fibonacci Numbers

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed n, find the sum of the even-valued terms. 

Solution:

function fiboEvenSum(n) {
  if(n <= 1) {
    return 0;
  }
  let evenSum = 0;
  let prevNum = 1;
  let curNum = 2;

  for(let i = 2curNum <= ni++) {
    if (curNum % 2 == 0) {
      evenSum += curNum;
    }
    [prevNumcurNum] = [curNumprevNum + curNum];
  }

  return evenSum;
}

fiboEvenSum(10)




Click here to go to the original link of the question.

Post a Comment

Previous Post Next Post