## How to find LCM of two numbers - Java Example

Write a program to find the LCM of two numbers in java is a popular question in ISC exam as well as in interviews of newly graduated candidates. This question basically checks your logic and knowledge of iteration, its overhead, breaking of loop etc.

We all know that LCM or the least common multiple of two or more non-zero whole numbers is actually the smallest whole number that is divisible by each of the numbers. In this tutorial we will see how to calculate LCM of two numbers using java.

### Java example to find LCM of two numbers

Following example shows how to find the LCM of the two numbers. Now lets see how we are finding LCM step by step.

1. We are taking two inputs from users and deciding min and max among those.

2. After deciding min and max of these two numbers, we will be iterating till the min number.

3. Then we are multiplying index to the max number. Then checking this value is fully divided by the min value.

4. If it is divisible then we get the LCM value for it. We can stop our iteration at this point.

### Simple java program to find LCM of two numbers

public class LCMTest {

public static void main(String[] args) {

try{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int num1, num2, maxNum, minNum, multiVal, lcm = 1;

System.out.print("Enter first number : ");

num1 = Integer.parseInt(br.readLine());

System.out.print("Enter second number : ");

num2 = Integer.parseInt(br.readLine());

if(num1 is greater than num2 )

{

maxNum=num1;

minNum=num2;

}

else

{

maxNum=num2;

minNum=num1;

}

for (int i = 1; i <= minNum; i++) {

multiVal = maxNum * i; // Getting multiples of the number

if (multiVal % minNum == 0) // Checking multiVal is divisible by minNum

{

lcm = multiVal; //Got the LCM value

break; //breaking the loop after getting LCM

}

}

System.out.println("L.C.M. of "+num1+" and "+num2+" is " + lcm);

}catch(Exception es){

System.out.println("es "+es.getLocalizedMessage());

}

}

}

Thus we have seen how to find LCM from two numbers in java.

## 0 comments:

## Post a Comment