Even Fibonacci Numbers Problem & Solution

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.

See the even Fibonacci numbers problem on Project Euler.

C++ Solution

#pragma GCC optimize("Ofast")
#pragma GCC optimization("unroll-loops")

#include <iostream>

using namespace std;

static const int _=[](){ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}();

int main() {
  int sum = 0;

  int first = 1;
  int second = 2;
  while (second < 4000000) {
    if (second % 2 == 0) {
      sum += second;
    }

    int tmp = first + second;
    first = second;
    second = tmp;
  }

  cout << sum << endl;
}

Start Here

Many paths, there are. Follow yours, you must.