License Public Domain
Lines 32
Keywords
Euler02 (5)
Permissions
Owner: msgordon
Group Owner: SnortSnort
Viewable by Everyone
Editable by msgordon

Euler02, C++ Atom Feed 1

# 's
 1/****************************************
2 Even Fibonacci numbers
3 Problem 2
4 Each new term in the Fibonacci sequence is generated by adding the previous
5two terms. By starting with 1 and 2, the first 10 terms will be:
6 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
7
8 By considering the terms in the Fibonacci sequence whose values do not
9exceed four million, find the sum of the even-valued terms.
10****************************************/
11
12#include <iostream>
13#include <cmath>
14
15using namespace std;
16
17/* Use Binet's formula to generate Fibonacci sequence.
18 Only add to sum if number is even. */
19
20int main()
21{
22 /* Golden ratio */
23 const double phi = (1.0 + sqrt(5.0))/2.0;
24 const int max_term = 4000000;
25
26 int sum = 0;
27 int a = 1;
28
29 for (int i = 0; a < max_term; i++)
30 {
31 /* (int) cast is like the floor function */
32 a = (int) ((pow(phi,i)/sqrt(5.0))+1.0/2.0);
33
34 if (a % 2 == 0)
35 sum += a;
36 }
37
38 cout << sum << endl;
39 return 0;
40}