Advertisement
avr39-ripe

fibonacciNew

Feb 29th, 2020
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.59 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. int fib(int n)
  4. {
  5.     if (n == 0) return 0;
  6.     if (n == 1) return 1;
  7.  
  8.     return fib(n - 1) + fib(n - 2);
  9. }
  10.  
  11. int fib1(int n)
  12. {
  13.     int res{ 0 };
  14.     int arr[2]{ 0 , 1 };
  15.  
  16.     if (n == 0) return 0;
  17.     if (n == 1) return 1;
  18.  
  19.     for (int i{ 2 }; i <= n; ++i)
  20.     {
  21.         res = arr[0] + arr[1];
  22.         arr[0] = arr[1];
  23.         arr[1] = res;
  24.     }
  25.     return res;
  26. }
  27.  
  28. int main()
  29. {
  30.     const int maxNum{ 45 };
  31.  
  32.     for (int i{ 0 }; i < maxNum; ++i)
  33.     {
  34.         std::cout << fib(i) << ' ';
  35.     }
  36.     std::cout << '\n';
  37.  
  38.     for (int i{ 0 }; i < maxNum; ++i)
  39.     {
  40.         std::cout << fib1(i) << ' ';
  41.     }
  42.     std::cout << '\n';
  43.  
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement