Euler Problem: Solution of Problem-2 in C++

Q) 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.

 

Image

Reference:

#include <iostream>

#define MAX 4000000

using namespace std;
/*
Series: 1 1 2 3 5 8 13 21 34 55 89 144 ...
Series we are interested in: 2 8 34 144 ...
we can see a relation for the above series:
f(0) = 2
f(1) = 8
f(n) = 4*f(n-1) + f(n-2)
Now we dont need any check for even/odd
*/
int main ( int argc, char *argv[] ) {
    unsigned long var_a = 2 ;
    unsigned long var_b = 8 ;
    unsigned long sum = 0 ;
    unsigned long temp = 0 ;
    while ( var_b < MAX ) {
        sum += var_b ;
        //cout << endl;
        temp = var_b ;
        var_b = ( 4 * var_b + var_a ) ;
        var_a = temp ;
    }
    cout << sum << endl;
}

Published by

Sreejith

A strong believer of: 1. Knowledge is power 2. Progress comes from proper application of knowledge 3. Reverent attains wisdom 4. For one's own salvation, and for the welfare of the world

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s