본문 바로가기
Programming/Project Euler

2. Project Euler #2 : Sum of even terms of Fibonacci.

by NoxLuna 2015. 1. 20.

Looking learn the C / C ++ language, just once, if it is to try the program, I would be the Fibonacci sequence. Comes on, but in places with a lot of Fibonacci recursion, is also often used as an example, the dynamic program is needed.

The Fibonacci sequence is required from the quiz form of increased geotinde a pair of rabbit populations. You can just adapt to growth in the same E. coli as a rabbit. The curves show the increase in geometric function.

The Fibonacci use a very simple ignition.

 

When the ignition is a very simple form. The sum of the preceding paragraph and the preceding paragraph is before the current term value.

So must be given to the first term and the second term is the initial value. The first term is 1, the second term is 1. Within the natural range Fibonacci proceed. Expand even further by creating a negative, but in this case I will to deal with the positive port.

Using a simple ignition, but a bit tricky to obtain a general term is harmful. All right aneuni how mathematical methodology not matter where, it hagoyo omitted. When obtaining a general term to express my expression as follows:

Creating as above, we can find two different a year. It can be easily obtained by using the roots of the quadratic formula. That it is the golden ratio values we often say. The Fibonacci sequence is also why I do not know that the famous. (Fibonacci prime numbers.)


We can get general Fibonacci numbers, using the solution.

Fibonacci general form is below.

If you ask for a large number in the Fibonacci term program if it is, it is necessary to heal using the general term of the above formula.

Only to obtain a general term Fibonacci program can be expressed as follows: Within the INT64 range, which may cause the actual error for a large number of bitter relation to double.


int64 fib(int n)
{
        double v = (pow(1+sqrt(5), n) - pow(1-sqrt(5), n))/pow(2.0, n)/sqrt(5);
        return (int64)(v+0.5);
}



Project Euler # 2 easy to use Fibonacci method in fact the normal way. If you want a little faster, please use the following. With an even number of values of the Fibonacci term occurs every third term. (Because odd + odd = even)
Therefore, we can derive the following new Fibonacci Fibonacci ignition using the original ignition.


Using this, Program will be below.

        int f1 = 2, f2 = 8;
        sum = 2;
        while( f2 <= 4000000 )
        {
                sum += f2;
                int t = f1+4*f2;
                f1 = f2;
                f2 = t;
        }
        printf("sum is %d\n", sum);




댓글