uHerbert : Pack 4 Level 5 Solution

Till now, the questions were easily solvable. Here comes a tougher one. I have to accept, this one took a fair amount of time for me to solve. So don’t you easily give up trying. This can be easily solved with a program of size 28 or 26 but we have a constraint of program size being 13. I started pulling my hair when I have a program of size 14 and at last when I found how to rephrase it to make it 13, I felt the joy of conquering the world.

Before going to the answer try to solve yourself. In between, if you need some tips or tricks, you are welcome to contact me(put your doubts below this blog and I shall help you). I assure you, you will be much more happier when you solve it by yourself.

Question :

Solve the below maize with a program of size 13.

uHerbert: Pack 4 question 5

Solution :

Screen Shot 2014-01-31 at 3.09.42 PM

For any clarifications: I am here; drop a comment ūüôā

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;
}