LCM in Java
Find the least common multiple of two numbers using GCD.
IntermediateModule 3: Loop ProgramsExample 12 of 25
lcm.java
1import java.util.Scanner;23public class Main {4 private static int gcd(int a, int b) {5 while (b != 0) {6 int temp = b;7 b = a % b;8 a = temp;9 }10 return a;11 }1213 public static void main(String[] args) {14 Scanner sc = new Scanner(System.in);15 System.out.print("Enter first number: ");16 int a = sc.nextInt();17 System.out.print("Enter second number: ");18 int b = sc.nextInt();1920 int g = gcd(a, b);21 int lcm = Math.abs(a * b) / g;22 System.out.println("LCM = " + lcm);23 sc.close();24 }25}
Output
Enter first number: 12 Enter second number: 18 LCM = 36
What's going on
We use the relation LCM(a, b) = |a × b| / GCD(a, b).