Java Program to Find GCD or HCF of Two Numbers

Last Updated : 5 Aug, 2026

The Greatest Common Divisor (GCD), also known as the Highest Common Factor (HCF), of two numbers is the largest positive integer that divides both numbers without leaving a remainder. Finding the GCD is useful in simplifying fractions, solving mathematical problems, cryptography, and many algorithmic applications.

  • The GCD of two co-prime numbers is 1.
  • The Euclidean Algorithm is the most efficient method for finding the GCD.

Illustration

Input: a = 12, b = 18
Output: GCD = 6

Input: a = 24, b = 36
Output: GCD = 12

Lightbox

Example:

HCF of 10 and 20 is 10, and HCF of 9 and 21 is 3. 

The GCD of two numbers can be efficiently computed using the Euclidean Algorithm. The algorithm is based on the principle that the GCD of two numbers does not change if the smaller number is subtracted from the larger number. A more efficient version uses the modulo operator.

Note: The GCD of two numbers remains unchanged when the smaller number is subtracted from the larger—this is the basis of the Euclidean algorithm.

Java
class GFG {
    // Gcd of x and y using recursive function
    static int GCD(int x, int y)
    {
        // If one number becomes 0, the other number is the GCD
        if (x == 0)
           return y;
           
        if (y == 0)
            return x;

        // Both the numbers are equal
        if (x == y)
            return x;

        // x is greater
        if (x > y)
            return GCD(x - y, y);
        return GCD(x, y - x);
    }

    // The Driver method
    public static void main(String[] args)
    {
        int x = 100, y = 88;
        System.out.println("GCD of " + x + " and " + y
                           + " is " + GCD(x, y));
    }
}

Output
GCD of 100 and 88 is 4

Explanation: In this example, the program uses the subtraction method to find the GCD of two numbers. It repeatedly subtracts the smaller number from the larger one until both numbers become equal. The common value obtained at the end is the Greatest Common Divisor (GCD) of the two numbers.

Java
class geeksforgeeks {
    // Function to return gcd of x and y
    // recursively
    static int GCD(int x, int y)
    {
        if (y == 0)
            return x;
        return GCD(y, x % y);
    }

    // The Driver code
    public static void main(String[] args)
    {
        int x = 47, y = 91;
        System.out.println("The GCD of " + x + " and " + y
                           + " is: " + GCD(x, y));
    }
}

Output
The GCD of 47 and 91 is: 1

Explanation: In this example, the program uses the Euclidean algorithm with the modulo (%) operator to efficiently calculate the GCD. It repeatedly replaces the larger number with the remainder of dividing it by the smaller number until the remainder becomes 0. The last non-zero value is the GCD. This method is faster and more efficient than the subtraction-based approach, especially for large numbers.

Comment