C++ solution to Project Euler Problem 2

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.

#include <iostream>
using namespace std;

int main()
{
	int total = 0;
	
	//3 variables to create the Fibonacci sequence from 1 to X
	int one = 1;
	int two = 2;
	int three = 0;
	
	while (two <= 4000000)
	{
		three = one + two;
		if (two % 2 == 0)
			total += two;
		one = two;
		two = three;
	}

	cout << total;

	return 0;
}

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

  1. 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. 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!

Leave a Reply

Your email address will not be published. Required fields are marked *