Advertisement
makispaiktis

Project Euler 2 - Even Fibonacci Numbers

Apr 11th, 2020 (edited)
401
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. /*
  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:
  3. 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
  4. By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
  5.  
  6. */
  7.  
  8. #include <iostream>
  9. #include <stdlib.h>
  10. #include <vector>
  11. #include <algorithm>
  12.  
  13. using namespace std;
  14.  
  15. int main()
  16. {
  17.     vector <int> fibonacci = vector <int> ();
  18.     fibonacci.push_back(0);
  19.     fibonacci.push_back(1);
  20.     while(fibonacci[fibonacci.size()-1] < 4000000){
  21.         fibonacci.push_back(fibonacci[fibonacci.size()-1] + fibonacci[fibonacci.size()-2]);
  22.     }
  23.     // When I come out the loop, there is a value up to 4M and I have to remove it
  24.     fibonacci.pop_back();
  25.     /*
  26.     for(unsigned int i=0; i<fibonacci.size(); i++){
  27.         cout << fibonacci[i] << endl;
  28.     }
  29.     */
  30.     int sum = 0;
  31.     for(unsigned int i=0; i<fibonacci.size(); i++){
  32.         if(fibonacci[i] % 2 == 0){
  33.             sum += fibonacci[i];
  34.         }
  35.     }
  36.     cout << "Sum = " << sum << endl;
  37.     return 0;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement