Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- /*
- Project Euler
- 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, ...
- Find the sum of all the even-valued terms in the sequence which do
- not exceed four million."
- */
- void main () {
- long number_limit = 4000000; // Find the sum of the...not exceed x
- long fibonacci_sequence [1000];
- long sum = 0;
- // Generate an array holding the fibonacci sequence
- fibonacci_sequence[0] = 1;
- fibonacci_sequence[1] = 2;
- long fibonacci_index = 2;
- while (fibonacci_sequence[fibonacci_index - 1] + fibonacci_sequence[fibonacci_index - 2] < number_limit) {
- fibonacci_sequence[fibonacci_index] = fibonacci_sequence[fibonacci_index - 1] + fibonacci_sequence[fibonacci_index - 2];
- fibonacci_index++;
- }
- // Now, find the sum of all even numbers in the sequence that are less
- // than 4 million.
- for (long i = 0; i < fibonacci_index; i++) {
- if (fibonacci_sequence[i] % 2 == 0 && fibonacci_sequence[i] < number_limit) {
- sum += fibonacci_sequence[i];
- }
- }
- cout << sum << endl;
- int stopCommandPromptFromClosing;
- cin >> stopCommandPromptFromClosing;
- }
Add Comment
Please, Sign In to add comment