Pejman Moghadam / C-programming

C++ - ProjectEuler.net, Problem 2

Public domain


/*
 * projecteuler.net, Problem 2 :
 * 
 * By considering the terms in the Fibonacci sequence whose values do not 
 * exceed four million, find the sum of the even-valued terms. 
 *
 * 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 <iomanip>

using namespace std;

main()
{
    const int max = 4000000;
    int sum = 0;

    for (int i = 1, j = 1; i < max; i += j) {
            // check for even number
            if (i % 2 == 0) {

                    // print plus sign before every number
                    // except the first one
                    if (sum != 0)
                            cout << " + ";

                    cout << i;
                    sum += i;
            }

            // swapping two variables
            i -= j += i -= j = -j;

    }

    cout << " = " << sum << endl;
}

Output :

2 + 8 + 34 + 144 + 610 + 2584 + 10946 + 46368 + 196418 + 832040 + 3524578 = 4613732

BY: Pejman Moghadam
TAG: cpp, mathematics, projecteuler
DATE: 2011-09-23 17:32:37


Pejman Moghadam / C-programming [ TXT ]