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;
}
- Include Libraries and Namespace:
The code includes the iostream library for input/output operations and uses the std namespace.
Define GCD Function:
The gcd function takes two integer parameters x and y and calculates the greatest common divisor using recursion.
Base Case Check:
If y is 0, the function returns x as the GCD.
Recursive Call:
If y is not 0, the function calls itself with arguments y and x % y.
Main Function:
- Initializes three integers x, y, and z with values 24, 36, and 48 respectively.
- Calls the gcd function with arguments x, y, and z to calculate the GCD of the three numbers.
- Outputs the calculated GCD.