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.

  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. 	int total = 0;
  7.  
  8. 	//3 variables to create the Fibonacci sequence from 1 to X
  9. 	int one = 1;
  10. 	int two = 2;
  11. 	int three = 0;
  12.  
  13. 	while (two <= 4000000)
  14. 	{
  15. 		three = one + two;
  16. 		if (two % 2 == 0)
  17. 			total += two;
  18. 		one = two;
  19. 		two = three;
  20. 	}
  21.  
  22. 	cout << total;
  23.  
  24. 	return 0;
  25. }

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 *