# Java Program to Find LCM of Two Numbers

Here you will get java program to find lcm of two numbers.

Finding LCM is one of the most basic mathematical calculations that are taught to students at their primary classes.

Let’s review the basic concepts again.

LCM stands for Least common multiple which simply means that it is a number that is divisible by all the given numbers.

This number i.e., LCM of the given numbers is always greater than or equal to the largest of given numbers. This is so because all the multiples of all the numbers are either equal to (number X1 = number) or greater than that number (number X2, X3 ….).

### Algorithm

To find the LCM of two numbers (or even more), we design a very simple algorithm to make our task easy.

**STEP 1:** Simply take the largest of all the numbers (here, two numbers only) as the LCM.

**STEP 2: **Start checking if LCM is divisible i.e., leaves remainder 0, when divided by all the numbers.

If true: Print the result and exit.

Else: increment LCM by 1.

**STEP 3: **Repeat STEP 2 infinite times.

## Java Program to Find LCM of Two Numbers

See how it looks like in a program.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import java.util.*; class FindLCMOfTwoNumbers { public static void main(String[] args) { Scanner key = new Scanner(System.in); int x,y; long lcm; System.out.println("Enter First Number"); x = key.nextInt(); System.out.println("Enter Second Number"); y = key.nextInt(); // initially take the lcm as the greatest number because lcm is always equal to or greater than the largest number. lcm = (x > y) ? x : y; // Take an infinite loop because loop count can't pe predicted. while(true) { //Check if the LCM is found and if true then print the LCM and break the loop. if( lcm % x == 0 && lcm % y == 0 ) { System.out.println("The LCM of " + x + " and " + y + " is : " + lcm); break; } ++lcm; } } } |

**Output**

*Enter First Number*

*5*

*Enter Second Number*

*10*

*The LCM of 5 and 10 is : 10*

Comment below if have queries regarding above program to find lcm in java.