Zachary Stence

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 four million, find the sum of the even-valued terms.

I first solved this problem September 2nd, 2014 in my AP Computer Science class in highschool. I do not have the original code I wrote, but I have redone the solution and included it below.

This problem was also fairly easy. I simply generated Fibonacci numbers until they reached four million, and added them to a sum if they were even. This code could also be optimized, but I prefer this simple version.

#include <iostream>

int main() {
  int sum = 0,
    a = 1,
    b = 1;
  while (b <= 4000000) {
    int fib = a + b;
    a = b;
    b = fib;
    if (fib % 2 == 0) sum += fib; 
  }
  std::cout << sum << std::endl;
}

Answer: 4613732