Flickyyy

DP Fibonacci

Aug 10th, 2021 (edited)
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <chrono>
  4. using namespace std;
  5. using namespace std::chrono;
  6. typedef unsigned long long ull;
  7.  
  8. //Simplest timer i can implement
  9. class Timer {
  10. public:
  11.     Timer() : start{ clock_t::now() } {}
  12.     void restart() {
  13.         start = clock_t::now();
  14.     }
  15.     double get_elapsed() const {
  16.         auto micro_elapsed = duration_cast<microseconds>(clock_t::now() - start).count();
  17.         return micro_elapsed / 1e3;
  18.     }
  19. private:
  20.     using clock_t = high_resolution_clock;
  21.     time_point<clock_t> start;
  22. };
  23.  
  24.  
  25. ull calls_fib = 0, calls_fib_dp = 0;
  26. vector<ull> fib_dp_res;
  27.  
  28. ull fib(ull pos) {
  29.     //we are counting the number of function calls
  30.     calls_fib += 1;
  31.  
  32.     // Fibonacci sequence starts with 0, then 1:
  33.     // Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21...
  34.     if (pos == 0) return 0;
  35.     if (pos == 1) return 1;
  36.     return fib(pos - 1) + fib(pos - 2);
  37. }
  38.  
  39. ull fib_dp(ull pos) {
  40.     //we are counting the number of function calls
  41.     calls_fib_dp += 1;
  42.  
  43.     if (pos < fib_dp_res.size())
  44.         return fib_dp_res[pos];
  45.     // Fibonacci sequence starts with 0, then 1:
  46.     // Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21...
  47.     if (pos == 0) {
  48.         fib_dp_res.push_back(0);
  49.         return fib_dp_res[pos];
  50.     }
  51.     fib_dp(pos - 1);
  52.     if (pos == 1 and fib_dp_res.size() == 1) {
  53.         fib_dp_res.push_back(1);
  54.         return fib_dp_res[pos];
  55.     }
  56.     fib_dp_res.push_back(fib_dp_res[pos - 1] + fib_dp_res[pos - 2]);
  57.     return fib_dp_res[pos];
  58. }
  59.  
  60. int main() {
  61.     ull position = 40;
  62.     ull fib_res, fib_dp_res;
  63.  
  64.     Timer fib_res_timer;
  65.     fib_res = fib(position);
  66.     auto fib_res_time = fib_res_timer.get_elapsed();
  67.  
  68.     Timer fib_dp_res_timer;
  69.     fib_dp_res = fib_dp(position);
  70.     auto fib_dp_res_time = fib_dp_res_timer.get_elapsed();
  71.  
  72.     cout << "fib(" << position << ") was called. Result is " << fib_res
  73.         << ". fib() was called " << calls_fib << " times." << " Elapsed time is: " << fib_res_time << " ms" << endl;
  74.  
  75.     cout << "fib_dp(" << position << ") was called. Result is " << fib_dp_res
  76.         << ". fib_dp() was called " << calls_fib_dp << " times." << " Elapsed time is: " << fib_dp_res_time << " ms" << endl;
  77. }
Add Comment
Please, Sign In to add comment