LCM of Two Numbers in Java with Explanation, Formula, Examples, and Program

The LCM of two numbers is the smallest number that is perfectly divisible by both. This article explains the concept with examples and provides a simple and efficient Java program.

LCM of Two Numbers in Java

The LCM (Least Common Multiple) of two numbers is the smallest positive integer that is divisible by both the numbers. A very efficient way to calculate the LCM is by using the GCD (Greatest Common Divisor).

Formula

LCM(a, b) = (a × b) / GCD(a, b)

This formula works because the product of two numbers is always equal to the product of their GCD and LCM.


Example

Find LCM of 12 and 18

So, the LCM of 12 and 18 is 36.


Java Program to Find LCM


public class LCM {

    // Function to calculate GCD using Euclidean Algorithm
    static int gcd(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }

    // Function to calculate LCM using the formula
    static int lcm(int a, int b) {
        return (a * b) / gcd(a, b);
    }

    public static void main(String[] args) {
        int num1 = 12;
        int num2 = 18;

        int result = lcm(num1, num2);
        System.out.println("LCM of " + num1 + " and " + num2 + " is: " + result);
    }
}

Practice Challenges

  1. Write a program to find the LCM of three numbers.
  2. Print all numbers between 1 and 100 whose LCM with 15 is less than 200.
  3. Modify the program to display both GCD and LCM along with the steps used to calculate them.