Advertisement
cacodemon665

Fibonacci

Jun 10th, 2019
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <time.h>
  4.  
  5. using namespace std;
  6.  
  7. // нулевой элемент - 1, первый элемент - 1, второй - 2
  8. int fibonacci_simple(int n)
  9. {
  10.     if (n == 0 || n == 1)
  11.     {
  12.         return 1;
  13.     }
  14.     else
  15.     {
  16.         return fibonacci_simple(n - 1) + fibonacci_simple(n - 2);
  17.     }
  18. }
  19.  
  20. int fibonacci_optimized(int n, vector<int>& arr)
  21. {
  22.     if (arr[n] == 0)
  23.     {
  24.         arr[n] = fibonacci_optimized(n - 1, arr) + fibonacci_optimized(n - 2, arr);
  25.     }
  26.  
  27.     return arr[n];
  28. }
  29.  
  30. int main()
  31. {
  32.     int n;
  33.  
  34.     cin >> n;
  35.  
  36.     cout << "fibonacci_simple(" << n <<  ") = ";
  37.     int t1 = clock();
  38.     cout << fibonacci_simple(n) << endl;
  39.     int t2 = clock();
  40.  
  41.     cout << double(t2 - t1) / CLOCKS_PER_SEC << "sec." << endl;
  42.  
  43.     cout << "fibonacci_optimized(" << n <<  ") = ";
  44.     t1 = clock();
  45.  
  46.     vector<int> arr(1000000, 0); // это шо то типа массива но умнее
  47.     arr[0] = arr[1] = 1;
  48.  
  49.     cout << fibonacci_optimized(n, arr) << endl;
  50.     t2 = clock();
  51.  
  52.     cout << double(t2 - t1) / CLOCKS_PER_SEC << "sec.";
  53.  
  54.  
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement