Advertisement
avr39ripe

SBU021RecursionBasic

Aug 1st, 2020
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. //n!= 1 * 2 * 3 * 4 ... n-1 * n
  4. //
  5. //n! = n * (n - 1)! = n * (n -1) * ( n - 1 - 1)! = n * (n - 1) * ( n - 1 -1 ) * ( n -1 -1 -1 )!
  6. //0! = 1;
  7.  
  8. /*
  9. 3! = 3 * (3-1)!
  10. (3-1)! = 2! = 2 * (2-1)!
  11. (2-1)! = 1! = 1 * (1-1)!
  12. (1-1)! = 0! = 1
  13.  
  14. 1! = 1;
  15. 2! = 2;
  16. 3! = 6;
  17.  
  18.  
  19. */
  20. /*
  21. fakt(3) -> 3 * fakt(2) -> 2 * fakt(1) -> 1 * fakt(0)
  22. fakt(0) => 1 * 1 -> fakt(1) => 1 * 2 -> fakt(2) => 2 -> 2*3 -> fakt(3) => 6
  23. */
  24.  
  25. //0! = 1;
  26. //n! = n * (n - 1)!
  27.  
  28.  
  29. int fakt(int n)
  30. {
  31.     if (n == 0) return 1;
  32.     return n * fakt(n - 1);
  33. }
  34.  
  35. int fib(int n)
  36. {
  37.     if (n == 0) return 0;
  38.     if (n == 1) return 1;
  39.     return fib(n - 1) + fib(n - 2);
  40. }
  41.  
  42. int fib1(int n)
  43. {
  44.     int res{ 0 };
  45.     int arr[2]{ 0,1 };
  46.     if (n == 0) return 0;
  47.     if (n == 1) return 1;
  48.     for (int i{ 2 }; i <= n; ++i)
  49.     {
  50.         res = arr[0] + arr[1];
  51.         arr[0] = arr[1];
  52.         arr[1] = res;
  53.     }
  54.     return res;
  55. };
  56.  
  57. int main()
  58. {
  59.     int maxNum{ 47 };
  60.     //std::cout << n <<"!=" << fakt(n) << '\n';
  61.     //std::cout << "FIB(" << n << ")=" << fib(n) << '\n';
  62.     //std::cout << "FIB1(" << n << ")=" << fib1(n) << '\n';
  63.  
  64.     //for(int i{0}; i<maxNum; ++i)
  65.     //{
  66.     //  std::cout << fib(i) << ' ';
  67.     //}
  68.  
  69.     std::cout << '\n';
  70.  
  71.     for (int i{ 0 }; i < maxNum; ++i)
  72.     {
  73.         std::cout << fib1(i) << ' ';
  74.     }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement