Start Coding Now
🔢 Number Programsintermediate2 methods

GCD and LCM of Two Numbers in Java

Find Greatest Common Divisor (GCD) and Least Common Multiple (LCM) of two numbers.

Last updated: 11 January 2026

Method 1: GCD using While Loop

Euclidean algorithm subtraction method.

public class GCD {
    public static void main(String[] args) {
        int n1 = 81, n2 = 153;
        
        while(n1 != n2) {
            if(n1 > n2)
                n1 -= n2;
            else
                n2 -= n1;
        }
        
        System.out.println("GCD: " + n1);
    }
}
Output:
GCD: 9

Explanation

Repeatedly subtract smaller number from larger until equal.

Method 2: LCM from GCD

Using formula LCM = (n1 * n2) / GCD.

public class LCM {
    public static void main(String[] args) {
        int n1 = 72, n2 = 120, gcd = 1;

        for(int i = 1; i <= n1 && i <= n2; ++i) {
            // Checks if i is factor of both integers
            if(n1 % i == 0 && n2 % i == 0)
                gcd = i;
        }

        int lcm = (n1 * n2) / gcd;
        System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
    }
}
Output:
The LCM of 72 and 120 is 360.

Explanation

First find GCD, then calculate LCM using the formula.

Frequently Asked Questions

Try This Program

Copy this code and run it in our free online Java compiler.

Open Java Compiler