# Java program to find LCM of two numbers

Let’s learn java program to find LCM of two numbers.

How to find lcm of two numbers is one of the common interview question in java. Well, first let us understand what is LCM??

Least Common Multiple(LCM)

Least Common Multiple is one of the mathematical algorithms. LCM of two numbers ‘a’ and ‘b’ is the smallest non zero positive integer that is divisible by both given numbers, that is, ‘a’ and ‘b’.

Here in the below java program, two numbers are stored in two variables. We have to set LCM to largest of two numbers. Because LCM cannot be less than largest number between two numbers.

Also read – string constructors in java

In while loop we check if LCM divides two numbers. If two numbers divides, LCM is found. Else increment LCM by 1.

## Java program to find lcm of two numbers

Now let’s see how to find lcm,

``````// lcm java
public class LCMOfTwoNumber
{
public static void main(String[] args)
{
int num1 = 85, num2 = 175, lcm;
lcm = (num1 > num2) ? num1 : num2;
while(true)
{
if(lcm % num1 == 0 && lcm % num2 == 0)
{
System.out.printf("LCM of " + num1 + " and " + num2 + " is " + lcm + ".");
break;
}
++lcm;
}
}
}

``````

Output:

LCM of 85 and 175 is 2975.

To calculate lcm two numbers in java we can use GCD. Here’s the formula,

LCM = (num1 * num2) / GCD

``````public class LCMUsingGCD
{
public static void main(String[] args)
{
int num1 = 15, num2 = 25, gcd = 1;
for(int a = 1; a <= num1 && a <= num2; ++a)
{
if(num1 % a == 0 && num2 % a == 0)
{
gcd = a;
}
}
int lcm = (num1 * num2) / gcd;
System.out.printf("LCM of " + num1 + " and " + num2 + " is " + lcm + ".");
}
}

``````

Output:

LCM of 15 and 25 is 75.