LCM of Two Numbers in Java
The LCM (Least Common Multiple) of two numbers is the smallest positive integer that is divisible by both the numbers. A very efficient way to calculate the LCM is by using the GCD (Greatest Common Divisor).
Formula
LCM(a, b) = (a × b) / GCD(a, b)
This formula works because the product of two numbers is always equal to the product of their GCD and LCM.
Example
Find LCM of 12 and 18
- GCD(12, 18) = 6
- LCM = (12 × 18) / 6
- LCM = 216 / 6 = 36
So, the LCM of 12 and 18 is 36.
Java Program to Find LCM
public class LCM {
// Function to calculate GCD using Euclidean Algorithm
static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
// Function to calculate LCM using the formula
static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
public static void main(String[] args) {
int num1 = 12;
int num2 = 18;
int result = lcm(num1, num2);
System.out.println("LCM of " + num1 + " and " + num2 + " is: " + result);
}
}
Practice Challenges
- Write a program to find the LCM of three numbers.
- Print all numbers between 1 and 100 whose LCM with 15 is less than 200.
- Modify the program to display both GCD and LCM along with the steps used to calculate them.