# LCM of two numbers using Java

## LCM of Two Numbers

Here, in this page we will discuss the LCM of two numbers using java. LCM is a Least Common Multiple, means LCM of two numbers is the number which is the smallest common multiple of both numbers. It is also referred to as the Lowest Common Multiple(LCM) or Least Common Denominator(LCD).

Or, the LCM of two numbers is the smallest number which can be divided by both numbers.For better understanding, let’s consider an example : –

Let’s say two numbers are 3 and 5, then

• Multiples of 3 are 3, 6, 9, 12, 15, 18, 21 …
• Multiples of 5 are 5, 10, 15, 20, 25, 30, 35 …

So, the lowest common multiple of 3 and 5 is 15, which is the LCM  of both numbers.

## Working :

Step 1 : Ask the user to enter two numbers and store in two different variables of same Datatype with name num1 and num2.

Step 2 : Use the condition to check which number is greater between first number and second number and store the result in a variable.

Step 3 : Use the loop to calculate the LCM of both numbers from a to (num1 * num2) , where a is the largest number among both numbers which are entered by the user and (num1 * num2) is the multiplication of the first number and the second number.

Step 4 : Print the result.

## Code for LCM of two numbers using Java :

`//Java program to find LCM of two numbersimport java.util.Scanner;public class lcm{	public static void main(String[] args)	{		//scanner class declaration		Scanner sc = new Scanner(System.in);		//input from the user				System.out.print("Enter the first number : ");				int num1 = sc.nextInt();		//input from the user		System.out.print("Enter the second number : ");				int num2 = sc.nextInt();		//logic for finding lcm of both numbers                int i;		int a =(num1 > num2)? num1 : num2;		for(i = a ; i <= num1*num2 ; i=i+a)		{			if(i % num1 == 0 && i % num2 == 0)				break;		}		//printing result		System.out.println("LCM of "+num1+" and "+num2+" is : "+i);		//closing scanner class(not compulsory, but good practice)		sc.close();										}}`

## Output :

`Enter the first number : 5Enter the second number : 8LCM of 5 and 8 is : 40`

### One comment on “LCM of two numbers using Java”

import java.util.*;
class LCM{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int num1=sc.nextInt();
int num2=sc.nextInt();
int gcd=1;
if(num1!=num2)
{
for(int i=1;i<=num1&&i<=num2;i++)
{
if(num1%i==0&&num2%i==0) gcd=i;
}
}
else System.out.println("enter different nuimbers");
System.out.println(gcd);
int lcm=(num1/gcd)*num2;
System.out.println("LCM= "+lcm);
}
}