summaryrefslogtreecommitdiff
path: root/p2/main.c
blob: b2d2a45ef124ab51efcf96b7b8a55628cd1c4726 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
 * 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 <stdio.h>
#include <math.h>

 #include "utils.h"

// /* http://www.evanmiller.org/mathematical-hacker.html */
// long int fib(unsigned long int n)
// {
//     return lround((pow(0.5 + 0.5 * sqrt(5.0), n) -
//                    pow(0.5 - 0.5 * sqrt(5.0), n)) / sqrt(5.0));
// }

// /* http://blog.noblemail.ca/2013/01/on-calculating-fibonacci-numbers-in-c.html */
// long int fib2(unsigned long int n)
// {
//     return lround((pow(0.5 + 0.5 * sqrt(5.0), n)) / sqrt(5.0));
// }

int main(int argc, char **argv)
{
    int i = 0;
    int last = 0;
    int sum = 0;

    last = fib(2);

    for (i = 3; last <= 4000000; i++)
    {
        /* even, if the lsb is 0 */
        if (!(last & 1))
        {
            sum += last;
        }

        last = fib(i);
    }

    printf("result: %d\n", sum);

    return 0;
}