Guest User

Untitled

a guest
Apr 26th, 2018
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. // Print n-Fibonacci number
  2. // 3 variants of realization
  3.  
  4. #include <iostream>
  5. #include <vector>
  6. #include <exception>
  7. #include <chrono>
  8. #include <ctime>
  9.  
  10. using namespace std;
  11.  
  12. // O(2^n)
  13. // The worst realization, too long:
  14. int GetFiboExponential(int n) {
  15. if (n < 2)
  16. return n;
  17. return GetFiboExponential(n - 1) + GetFiboExponential(n - 2);
  18. }
  19.  
  20. // O(n)
  21. // Ok but additional O(n) memory used:
  22. int GetFiboLinear(int n) {
  23. if (n < 2)
  24. return n;
  25. vector<int> result(n + 1, 0);
  26. for (int i = 0; i <= n; ++i)
  27. if (i < 2)
  28. result[i] = i;
  29. else
  30. result[i] = result[i-1] + result[i-2];
  31. return result.back();
  32. }
  33.  
  34. // O(n)
  35. // Good, no additional memory:
  36. int GetFibo(int n) {
  37. int n_2 = 0;
  38. int n_1 = 1;
  39. int f = n;
  40. for (int i = 1; i < n; ++i) {
  41. f = n_2 + n_1;
  42. n_2 = n_1;
  43. n_1 = f;
  44. }
  45. return f;
  46. }
  47.  
  48. template <typename FuncType>
  49. void CountTimeOfFibo(FuncType func, int n) {
  50. clock_t start = clock();
  51. cout << "\t" << func(n);
  52. cout << ", time = ";
  53. cout << chrono::duration<double, std::milli>(clock() - start).count();
  54. cout << " ms" << endl;
  55. }
  56.  
  57. void check(int n) {
  58. if (n < 0)
  59. throw std::runtime_error("Invalid input data");
  60. }
  61.  
  62. int main() {
  63. while (true) {
  64. cout << "Enter number: ";
  65. int n;
  66. cin >> n;
  67. check(n);
  68. cout << "Fibonacci number is:" << endl;
  69. CountTimeOfFibo(GetFiboExponential, n);
  70. CountTimeOfFibo(GetFiboLinear, n);
  71. CountTimeOfFibo(GetFibo, n);
  72. }
  73. return 0;
  74. }
Add Comment
Please, Sign In to add comment