Java Program to Find LCM of Two Numbers

Last Updated : 5 Aug, 2026

The Least Common Multiple (LCM) of two numbers is the smallest positive number that is exactly divisible by both numbers. LCM is commonly used in mathematics, fractions, scheduling problems, and algorithmic computations where a common multiple of two values is required.

  • LCM is the smallest positive number divisible by both given numbers.
  • It is always greater than or equal to the larger of the two numbers.

Illustration:

Input: a = 12, b = 18
Output: LCM = 36

Input: a = 15, b = 20
Output: LCM = 60

lcm in java

Program to Find the LCM of Two Numbers

The easiest approach for finding the LCM is to Check the factors and then find the Union of all factors to get the result.

Java
import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        int a = 15, b = 25;

        // Checking for the largest
        // Number between them
        int ans = (a > b) ? a : b;

        // Checking for a smallest number that
        // can be divided by both numbers
        while (true) {
            if (ans % a == 0 && ans % b == 0)
                break;
            ans++;
        }

        // Printing the Result
        System.out.println("LCM of " + a + " and " + b
                           + " : " + ans);
    }
}

Output
LCM of 15 and 25 : 75

Explanation: In this example, the program starts by selecting the larger of the two numbers as the initial candidate for the LCM. It then repeatedly checks whether the current number is divisible by both input numbers. If not, the candidate is incremented until a number divisible by both is found. That number is the Least Common Multiple (LCM).

Using Greatest Common Divisor

Below given formula for finding the LCM of two numbers ‘u’ and ‘v’ gives an efficient solution.

u x v = LCM(u, v) * GCD (u, v)

LCM(u, v) = (u x v) / GCD(u, v)

Here, GCD is the greatest common divisor.

Java
class gfg {
    // Gcd of u and v
    // using recursive method
    static int GCD(int u, int v)
    {
        if (u == 0)
            return v;
        return GCD(v % u, u);
    }

    // LCM of two numbers
    static int LCM(int u, int v)
    {
        return (u / GCD(u, v)) * v;
    }

    // main method
    public static void main(String[] args)
    {
        int u = 25, v = 15;
        System.out.println("LCM of " + u + " and " + v
                           + " is " + LCM(u, v));
    }
}
Try It Yourself
redirect icon

Output
LCM of 25 and 15 is 75

Explanation: In this example, the program first calculates the Greatest Common Divisor (GCD) of the two numbers using a recursive method. It then uses the formula LCM = (a × b) / GCD(a, b) to efficiently compute the LCM. This approach is faster and more efficient than checking multiples one by one, especially for large numbers.

Comment