Guest User

Untitled

a guest
Jun 21st, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. /*
  5.  
  6. Project Euler
  7. Problem 2:
  8. "Each new term in the Fibonacci sequence is generated by adding the
  9. previous two terms. By starting with 1 and 2, the first 10 terms will
  10. be:
  11. 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
  12. Find the sum of all the even-valued terms in the sequence which do
  13. not exceed four million."
  14.  
  15. */
  16.  
  17. void main () {
  18.  
  19. long number_limit = 4000000; // Find the sum of the...not exceed x
  20. long fibonacci_sequence [1000];
  21. long sum = 0;
  22.  
  23. // Generate an array holding the fibonacci sequence
  24. fibonacci_sequence[0] = 1;
  25. fibonacci_sequence[1] = 2;
  26.  
  27. long fibonacci_index = 2;
  28. while (fibonacci_sequence[fibonacci_index - 1] + fibonacci_sequence[fibonacci_index - 2] < number_limit) {
  29. fibonacci_sequence[fibonacci_index] = fibonacci_sequence[fibonacci_index - 1] + fibonacci_sequence[fibonacci_index - 2];
  30.  
  31. fibonacci_index++;
  32. }
  33.  
  34. // Now, find the sum of all even numbers in the sequence that are less
  35. // than 4 million.
  36. for (long i = 0; i < fibonacci_index; i++) {
  37. if (fibonacci_sequence[i] % 2 == 0 && fibonacci_sequence[i] < number_limit) {
  38. sum += fibonacci_sequence[i];
  39. }
  40.  
  41. }
  42.  
  43. cout << sum << endl;
  44.  
  45. int stopCommandPromptFromClosing;
  46. cin >> stopCommandPromptFromClosing;
  47.  
  48. }
Add Comment
Please, Sign In to add comment