C Implementation of Problem 2
View source code here on GitHub!
Includes
"macros.h" (implicitly, via digits.h)
"iterator.h" (implicitly, via digits.h)
"math.h" (implicitly, via digits.h & if compiled on PCC)
<stdbool.h>
(implicitly, via digits.h)<stdlib.h>
(implicitly, via digits.h & if not compiled on PCC)<math.h>
(implicitly, via digits.h & if not compiled on PCC)
Solution
-
uint32_t p0002()
-
int main(int argc, char const *argv[])
Note
This function is only present in the Python test runner, or when compiling as a standalone program. It is not present when compiling for the Unity test runner.
1/*
2Project Euler Problem 2
3
4More iterator usage
5
6Problem:
7
8Each new term in the Fibonacci sequence is generated by adding the previous two
9terms. By starting with 1 and 2, the first 10 terms will be:
10
111, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
12
13By considering the terms in the Fibonacci sequence whose values do not exceed
14four million, find the sum of the even-valued terms.
15*/
16
17#ifndef EULER_P0002
18#define EULER_P0002
19#include <stdint.h>
20#include <inttypes.h>
21#include <stdio.h>
22#include "include/macros.h"
23#include "include/fibonacci.h"
24
25uint32_t EMSCRIPTEN_KEEPALIVE p0002() {
26 uint32_t answer = 0;
27 fibonacci fib = fibonacci1(3999999);
28 while (!fib.exhausted) {
29 next(fib); // odd (1, 3, 13, 55, ...)
30 next(fib); // odd (1, 5, 21, 89, ...)
31 answer += next(fib); // even (2, 8, 34, 144, ...)
32 }
33 return answer;
34}
35
36PROGRAM_TAIL("%" PRIu32, p0002)
37#endif