# 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.

#include <iostream>

#include <vector>

using namespace std;

int main()

{

vector<int> fib;

int first = 1;

int second = 2;

fib.push_back(first);

fib.push_back(second);

int currentFib = 0;

while(1)

{

if(currentFib >= 4000000)

{

break;

}

currentFib = first + second;

fib.push_back(currentFib);

first = second;

second = currentFib;

}

int sum = 0;

for (int i = 0; i < fib.size(); i++)

{

if (fib[i] % 2 == 0)

sum = sum + fib[i];

}

cout << sum;

}

Solution: 4613732

Last modified 3yr ago