-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0002_even_fibonacci_numbers.cpp
More file actions
53 lines (41 loc) · 1.68 KB
/
0002_even_fibonacci_numbers.cpp
File metadata and controls
53 lines (41 loc) · 1.68 KB
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
52
53
/**********************
Author: Daniel Bowder
Date: July 16, 2018
Problem: https://projecteuler.net/problem=2
"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 <iostream>
#include <cmath>
using std::cout;
using std::endl;
long double even_fibonacci_numbers(long double valueMax) {
// Setup our sum variable to add our conditional Fibonacci Numbers to.
long double sum = 0;
// Setup our Fibonacci numbers. valueA = n valueB = (n - 1)
double valueA = 1;
double valueB = 1;
// ** Value B will hold the valueA from the prior calculation, so that,
// in the spirit of the Fibonacci sequence, we can add the current value,
// to the prior value in the sequence.
// Setup our temprary variable to hold valueA, later to transfer to valueB.
double valueTemp;
for (int i=0; valueA < valueMax; i++) {
// If Fibonacci Number is evenly divisible by 2,
if (0 == fmod(valueA, 2)) {
// add the current Fibonacci Number to the sum.
sum = sum + valueA;
}
// Incriment the Fibonacci Counter
valueTemp = valueA; // Store valueA so that we can update valueA.
valueA = valueA + valueB; // Update valueA
valueB = valueTemp; // Assign valueB to the value of valueA before we updated valueA.
}
return sum;
}
int main(int argc, char* argv[]) {
cout << "Problem 2. " << even_fibonacci_numbers(4000000) << endl;
}