gcd function c++
#include <iostream>
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int main() {
int num1, num2;
std::cout << "Enter two numbers: ";
std::cin >> num1 >> num2;
int result = gcd(num1, num2);
std::cout << "GCD of " << num1 << " and " << num2 << " is " << result << std::endl;
return 0;
}
The above code defines a gcd
function in C++ that calculates the greatest common divisor (GCD) of two integers using the Euclidean algorithm. The gcd
function takes two parameters a
and b
and recursively calls itself with b
and a % b
until b
becomes 0, at which point it returns a
.
In the main
function, the user is prompted to enter two numbers. These numbers are then passed as arguments to the gcd
function, and the result is stored in the result
variable. Finally, the result is printed to the console.