LCM

Find the least common multiple of two numbers using GCD.

JavaIntermediate
Java
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

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