LCM

Find the least common multiple of two numbers using GCD.

IntermediateTopic: Module 3: Loop Programs
Back

Java LCM Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
import java.util.Scanner;

public class Main {
    private static int gcd(int a, int b) {
        while (b != 0) {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter first number: ");
        int a = sc.nextInt();
        System.out.print("Enter second number: ");
        int b = sc.nextInt();

        int g = gcd(a, b);
        int lcm = Math.abs(a * b) / g;
        System.out.println("LCM = " + lcm);
        sc.close();
    }
}
Output
Enter first number: 12
Enter second number: 18
LCM = 36

Understanding LCM

We use the relation LCM(a, b) = |a × b| / GCD(a, b).

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents