Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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 <stdlib.h>
- #include <vector>
- #include <algorithm>
- using namespace std;
- int main()
- {
- vector <int> fibonacci = vector <int> ();
- fibonacci.push_back(0);
- fibonacci.push_back(1);
- while(fibonacci[fibonacci.size()-1] < 4000000){
- fibonacci.push_back(fibonacci[fibonacci.size()-1] + fibonacci[fibonacci.size()-2]);
- }
- // When I come out the loop, there is a value up to 4M and I have to remove it
- fibonacci.pop_back();
- /*
- for(unsigned int i=0; i<fibonacci.size(); i++){
- cout << fibonacci[i] << endl;
- }
- */
- int sum = 0;
- for(unsigned int i=0; i<fibonacci.size(); i++){
- if(fibonacci[i] % 2 == 0){
- sum += fibonacci[i];
- }
- }
- cout << "Sum = " << sum << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement