Java Programs

LCM Program in Java with Explanations

In this tutorial, we are going to learn java program to calculate the least common multiple of two numbers.

Our program will take two numbers as the input from the user and return the LCM of input numbers.

For example

if the user inputs the numbers 4 and 6. then the output should be ‘12’ as 12 is the LCM of 4 and 6.

Java Program to calculate LCM of two numbers

import java.util.*;

public class Main {
	
    public static void main(String[] args) {
        double num1,num2,maxNum;
        System.out.println("Java Program to calculate LCM" );
        Scanner sc = new Scanner(System.in);
        System.out.println("Please give first number");
        num1= sc.nextDouble();
        System.out.println("Please give second number");
        num2 = sc.nextDouble();
        maxNum = (num1 > num2) ? num1 : num2;
        
        while (true) {
            if (maxNum % num1 == 0 && maxNum % num2 == 0) {
            System.out.println("LCM = "+maxNum );
            break;
        }
        ++maxNum;
    }
 }
}

Output

Java Program to calculate LCM
Please give first number
3
Please give second number
4
LCM = 12.0

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs