Google News
logo
C++ Program to Find G.C.D Using Recursion
In the following example of C++ program to find the greatest common divisor (GCD) of two numbers using recursion :
Program :
#include <iostream>
using namespace std;

int gcd(int a, int b) {
    if (b == 0) {
        return a;
    } else {
        return gcd(b, a % b);
    }
}

int main() {
    int a, b;

    cout << "Enter two positive integers: ";
    cin >> a >> b;

    cout << "The GCD of " << a << " and " << b << " is " << gcd(a, b) << endl;

    return 0;
}
Output :
Enter two positive integers: 345 70
The GCD of 345 and 70 is 5
This program defines a recursive function called gcd that takes two positive integers a and b as its arguments. If b is 0, the function returns a; otherwise, it returns the result of calling gcd with b and the remainder of a divided by b. In main(), the user is prompted to enter two positive integers, and the gcd function is called with those integers as its arguments. The GCD is then printed out.