Facebook
From ب, 1 Month ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 119
  1. #include <iostream>
  2. #include <chrono>
  3. using namespace std;
  4. using namespace std::chrono; // Ensure namespace for chrono elements is included
  5.  
  6. // Recursive Fibonacci function
  7. int fibr(int n) {
  8.     if (n <= 1)
  9.         return n;
  10.     return fibr(n - 1) + fibr(n - 2);
  11. }
  12.  
  13. // Iterative Fibonacci function
  14. int fibi(int n) {
  15.     int a = 0, b = 1, c;
  16.     if (n == 0) {
  17.         return a;
  18.     }
  19.     for (int i = 2; i <= n; i++) {
  20.         c = a + b;
  21.         a = b;
  22.         b = c;
  23.     }
  24.     return b;
  25. }
  26.  
  27. int main() {
  28.     int n = 50; // Consider lowering this for recursive calculations, or limiting recursive calls
  29.     for (int i = 1; i <= n; i++) {
  30.         // Measure recursive Fibonacci
  31.         auto startR = high_resolution_clock::now();
  32.         cout << "Recursive:\n";
  33.         cout << "fib(" << i << ")=" << fibr(i) << " ";
  34.         auto stopR = high_resolution_clock::now();
  35.          auto durati>(stopR - startR);
  36.         cout << "Time: " << durationR.count() << " microseconds\n";
  37.  
  38.         // Measure iterative Fibonacci
  39.         auto startI = high_resolution_clock::now();
  40.         cout << "Iterative:\n";
  41.         cout << "fib(" << i << ")=" << fibi(i) << " ";
  42.         auto stopI = high_resolution_clock::now();
  43.          auto durati>(stopI - startI);
  44.         cout << "Time: " << durationI.count() << " microseconds\n";
  45.     }
  46.     return 0;
  47. }