Problem 2: Even Fibonacci Numbers

The Fibonacci sequence starts with 1 and 2, then repeatedly applies to produce

We focus on terms whose value does not exceed and ask for the sum of the even-valued members. This constraint keeps the set finite while highlighting the pattern that every third Fibonacci term is even.

How to Solve

Maintain two rolling values for consecutive Fibonacci terms. While the second value stays below the user-provided limit, add it to the sum whenever .

Advance the sequence in-place by computing the next term, moving the window forward, and repeating until the limit is exceeded. The loop generates exactly as many numbers as needed, so the runtime grows linearly with the number of terms considered () and uses constant extra memory.

Code Solution


function fiboEvenSum(limit: number): number {
  let a = 1;
  let b = 2;
  let sum = 0;

  while (b <= limit) {
    if (b % 2 === 0) {
      sum += b;
    }
    const next = a + b;
    a = b;
    b = next;
  }
  return sum;
}

Test the Solution