Java Program to Find LCM of Two Numbers

Last Updated : 19 Mar, 2026

LCM (Least Common Multiple) is the smallest positive number that both given numbers divide exactly (without leaving any remainder).

lcm in java

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

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
Comment