Project Euler Problem 2


/ Published in: C++
Save to your folder(s)

Sorted via problem ID.


Copy this code and paste it in your HTML
  1. /*
  2. Alexander DeTrano
  3. 2/1/2010
  4. Project Euler - Problem 2
  5.  
  6. 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:
  7.  
  8. 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
  9.  
  10. By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
  11. */
  12.  
  13. #include <iostream>
  14. #include <vector>
  15.  
  16. using namespace std;
  17.  
  18. int fib(int n);
  19.  
  20. int main() {
  21.  
  22. vector<int> myArray; //declare vector to store Fibonacci numbers
  23.  
  24. int s=34; // Size needed for vector length
  25. int sum=0; //Initialize sum to 0
  26.  
  27. //Generate Fibonacci numbers and store in array, add every third
  28. for(int i=0; i<s; i++){
  29. myArray.push_back(i);
  30. if (i%3 == 0){
  31. myArray[i]=fib(i);
  32. cout<< "fib(" << i << ")= " << myArray[i] << " \n";
  33. sum+=myArray[i];
  34. cout<<" Sum = "<< sum <<"\n";
  35. }
  36. }
  37.  
  38. cout<<"Total sum = " << sum;
  39. }
  40.  
  41. // Function to generate Fibonacci numbers
  42. int fib(int n)
  43. {
  44. if ( n==0 ) return 0;
  45. if ( n==1 ) return 1;
  46.  
  47. /*for(int i=0;i<5;i++){
  48. z= fib(n-1) + fib(n-2);
  49. */
  50. return fib(n-1) + fib(n-2);
  51. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.