C++ Program to Find GCD

The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both of them without leaving a remainder.

For example, let's say we have two numbers 45 and 27 −

45 = 5 * 3 * 3
27 = 3 * 3 * 3

The common factors are 3 and 3, so the GCD of 45 and 27 is 9.

Using Euclidean Algorithm (Modulo Method)

The Euclidean algorithm finds the GCD by repeatedly replacing the larger number with the remainder of dividing the two numbers, until the remainder becomes 0. At that point, the other number is the GCD ?

Example

#include <iostream>
using namespace std;

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

int main() {
    int a = 105, b = 30;
    cout << "GCD of " << a << " and " << b << " is " << gcd(a, b);
    return 0;
}

The output of the above code is ?

GCD of 105 and 30 is 15

In the gcd() function, if b is 0, then a is the GCD and is returned. Otherwise, the function recursively calls itself with b and a % b. For example, gcd(105, 30) calls gcd(30, 15), which calls gcd(15, 0), returning 15.

Using Subtraction Method

Another approach is to repeatedly subtract the smaller number from the larger one until both become equal. That equal value is the GCD ?

Example

#include <iostream>
using namespace std;

int gcd(int a, int b) {
    if (a == 0 || b == 0)
        return 0;
    else if (a == b)
        return a;
    else if (a > b)
        return gcd(a - b, b);
    else
        return gcd(a, b - a);
}

int main() {
    int a = 105, b = 30;
    cout << "GCD of " << a << " and " << b << " is " << gcd(a, b);
    return 0;
}

The output of the above code is ?

GCD of 105 and 30 is 15

In this version, if a or b is 0, the function returns 0. If they are equal, that value is the GCD. Otherwise, the function subtracts the smaller from the larger and recurses. This is slower than the modulo method for large numbers but illustrates the concept clearly.

Conclusion

Both approaches use recursion to find the GCD. The Euclidean algorithm using modulo (a % b) is more efficient, while the subtraction method is easier to understand conceptually. For production code, prefer the modulo approach or use the built-in __gcd() function available in C++.

Updated on: 2026-03-12T23:28:57+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements