### Java Program to Find LCM of Two Numbers - The Coding Shala

Home >> Java Programs >> Find LCM of Two Numbers

Hey there, welcome back to another post. In this post, we will learn how to find the LCM of two numbers in Java.

## Java Program to Find LCM of Two Numbers

The LCM (Least Common Multiple) is the smallest number that can be divided by both numbers. For example, the LCM of 5 and 10 is 10 because 10 is the smallest number that is divisible by both 5 and 10.

Example 1:

```Input
Number1: 8
Number2: 10

Output
LCM of 8 and 10 is: 40
```

## Find LCM of Two Numbers using GCD

We can find the LCM of two numbers by using GCD. The relation between LCM and GCD is:

```   a x b = LCM(a, b) * GCD (a, b)

LCM(a, b) = (a x b) / GCD(a, b)
```

For example, LCM(8, 10) is:

LCM(8, 10) = ( 8 * 10) / GCD(8,10)

LCM(8, 10) = 80 / 2 = 40

Java Program:

```import java.util.Scanner;

/**
* https://www.thecodingshala.com/
*/

public class Main {

public static int findGCD(int num1, int num2) {
if (num1 == 0) {
return num2;
}

if (num2 == 0) {
return num1;
}

while (num1 != num2) {
if (num1 > num2) {
num1 = num1 - num2;
} else {
num2 = num2 - num1;
}
}

return num1;
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
int num1 = sc.nextInt();
System.out.println("Enter second number");
int num2 = sc.nextInt();

int gcd = findGCD(num1, num2);
int lcm = (num1 * num2) / gcd;
System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm);
}
}
```

Output:

```Enter first number
15
Enter second number
25
LCM of 15 and 25 is: 75
```

## Find LCM of Two Number using Java for Loop

We can find the LCM of two numbers using Java for Loop.

Java Program:

```import java.util.Scanner;

/**
* https://www.thecodingshala.com/
*/

public class Main {

public static int findLCM(int num1, int num2) {
int max = Math.max(num1, num2);
int lcm;
for (lcm = max; lcm <= num1 * num2; lcm = lcm + max) {
if (lcm%num1 == 0 && lcm%num2 == 0) {
break;
}
}
return lcm;
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number");
int num1 = sc.nextInt();
System.out.println("Enter second number");
int num2 = sc.nextInt();

int lcm = findLCM(num1, num2);
System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm);
}
}
```

Output:

```Enter first number
15
Enter second number
25
LCM of 15 and 25 is: 75
```

Other Posts You May Like