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

  1. LCM(a,b) = (a * b) / GCD(a,b)
  2. First calculate GCD, then use it for LCM
  3. Be careful of integer overflow for large numbers

Related Core Java Basics exercises

Practice all Core Java Basics exercises · Run this idea in the Java compiler