Least Common Multiple in Java: Explanation & Practice
Find LCM of two numbers
Problem summary
Write a program that finds the Least Common Multiple (LCM) of two numbers.
Starter code
public class Main {
public static void main(String[] args) {
int a = 12;
int b = 18; // Test case 1
// Find LCM (hint: LCM = a*b / GCD)
// Print: LCM: <result>
}
}Expected output and test cases
- LCM(12, 18) = 36
LCM: 36
- LCM(6, 10) = 30
LCM: 30
- LCM(5, 7) = 35
LCM: 35
Hints
- LCM(a,b) = (a * b) / GCD(a,b)
- First calculate GCD, then use it for LCM
- Be careful of integer overflow for large numbers
Related Core Java Basics exercises
- Practice Palindrome Number Check in Java
- Practice Greatest Common Divisor in Java
- Practice Armstrong Number Check in Java
Practice all Core Java Basics exercises · Run this idea in the Java compiler