# C++ solution to Project Euler Problem 2

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.

Running time: Unknown

Assessment: Inelegant.

This took me an embarrassingly long time to get right. With the exception of Problem 1, I hadn’t written any code in a few years. As noted before, I hadn’t started measuring execution time yet, so I’m not sure how long it took to run, but it’s basically instantaneous.

## 3 thoughts on “C++ solution to Project Euler Problem 2”

1. Firestorm says:

Thankyou for this. I was trying to make a vector and sum each number in the vector! I couldn’t achieve this method, too advanced, when the answer was so simple with an if statement! Thanks!

2. Surya Teja says:

why is the while loop only upto 4000000

3. hendog says:

I did it slightly differently, my version used only two variables:
a += b;
b += a;
if (a % 2 == 0){ total += a;}
if (b % 2 == 0){total += b;}

this is what was in my while loop, I think yours is a little more elegant though, I am a beginner and I love seeing people write the same solution more efficiently, it is always a learning experience
Thanks!