Advertisement
bogdanNiculeasa

Recursive examples

Mar 29th, 2021
703
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.98 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int computeGCD(int a, int b);
  6. int computeGCDRecursive(int a, int b);
  7. double computeFactorial(int n);
  8. double computeFactorialRecursive(int n);
  9.  
  10. int main() {
  11.  
  12.     //GCD = > Greatest Common Divisor
  13.     cout << computeGCD(21, 49);
  14.  
  15.     return 0;
  16. }
  17.  
  18. int computeGCD(int a, int b) {
  19.     while (b != 0) {
  20.         int temp = b;
  21.         b = a % b;
  22.         a = temp;
  23.     }
  24.     return a;
  25. }
  26.  
  27. int computeGCDRecursive(int a, int b) {
  28.     //1. Conditia de oprire
  29.     if (b == 0) {
  30.         return a;
  31.     }
  32.  
  33.     //2 Apelul recursive
  34.     return computeGCDRecursive(b, a % b);
  35. }
  36.  
  37.  
  38.  
  39. // Compute factorial: n! => 1 * 2 * 3 *.. *n => 4! => 4 * 3!
  40.  double computeFactorial(int n) {
  41.      double result = 1;
  42.      for (int i = 1; i <=n;i++) {
  43.          result = result * i;
  44.      }
  45.      return result;
  46.  }
  47.  
  48.  double computeFactorialRecursive(int n) {
  49.     if (n <= 1) {
  50.         return 1;
  51.     }
  52.  
  53.     return n * computeFactorialRecursive(n-1);
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement