Java Program to Find LCM of two Numbers

Java Program to Find LCM of two Numbers

In this example, we will learn to find the lcm of two number by using GCD

The LCM of two integers is the smallest positive integer that is perfectly divisible by both the numbers (without a remainder).

Example 1: LCM

public class LCM {
    public static void main(String[] args) {

        int n1 = 32, n2 = 120, lcm;

        // maximum number between n1 and n2 is stored in lcm
        lcm = (n1 > n2) ? n1 : n2;

        // Always true
        while(true)
        {
            if( lcm % n1 == 0 && lcm % n2 == 0 )
            {
                System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
                break;
            }
            ++lcm;
        }
    }
}

Output :  The LCM of 32 and 120 is 480

We can also use GCD to find the LCM of two numbers using the following formula:

LCM = (n1 * n2) / GCD

Example 2: Calculate LCM using GCD

public class LCM {
    public static void main(String[] args) {

        int n1 = 32, 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 32 and 120 is 480