C++ Implementation of Problem 2
View source code here on GitHub!
Includes
Solution
-
uint64_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.
1/*
2Project Euler Problem 2
3
4Again, see Python implementation for a proof
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 <iostream>
21#include "include/macros.hpp"
22
23uint64_t EMSCRIPTEN_KEEPALIVE p0002() {
24 uint64_t answer = 0,
25 a = 1, b = 2, t;
26 while (b < 4000000) {
27 // odd (1, 3, 13, 55, ...)
28 // odd (1, 5, 21, 89, ...)
29 // even (2, 8, 34, 144, ...)
30 answer += b;
31 for (uint8_t z = 0; z < 3; z++) {
32 t = b;
33 b = a + b;
34 a = t;
35 }
36 }
37 return answer;
38}
39
40
41PROGRAM_TAIL(p0002)
42#endif