GCD(x, yz)

GCD Calculation in C++

#include <iostream>
using namespace std;

int gcd(int x, int y) {
    if (y == 0) {
        return x;
    } else {
        return gcd(y, x % y);
    }
}

int main() {
    int x = 24, y = 36, z = 48;
    int result = gcd(x, gcd(y, z));
    cout << "GCD of " << x << ", " << y << " and " << z << " is " << result << endl;
    return 0;
}
  1. Include Libraries and Namespace:
  2. The code includes the iostream library for input/output operations and uses the std namespace.

  3. Define GCD Function:

  4. The gcd function takes two integer parameters x and y and calculates the greatest common divisor using recursion.

  5. Base Case Check:

  6. If y is 0, the function returns x as the GCD.

  7. Recursive Call:

  8. If y is not 0, the function calls itself with arguments y and x % y.

  9. Main Function:

  10. Initializes three integers x, y, and z with values 24, 36, and 48 respectively.
  11. Calls the gcd function with arguments x, y, and z to calculate the GCD of the three numbers.
  12. Outputs the calculated GCD.