Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

LCM in Java

Calculate LCM in Java using a remainder-based GCD helper and a long product. Divide before multiplying; zero input returns zero without dividing by zero.

IntermediateJava Loop ProgramsExample 12 of 25
lcm.java
1import java.util.Scanner;
2
3public 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 }
12
13 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();
19
20 int g = gcd(a, b);
21 long lcm = (a == 0 || b == 0) ? 0 : Math.abs(((long) a / g) * b);
22 System.out.println("LCM = " + lcm);
23 sc.close();
24 }
25}

Sample Output

Enter first number: 12
Enter second number: 18
LCM = 36

gcd(12,18) is 6. Then (12 / 6) * 18 = 36.

In this one

  • Relate LCM to GCD
  • Handle a zero input before division
  • Widen a multiplication in time

How it works

  1. 1

    Read a and b.

  2. 2

    Calculate their GCD g.

  3. 3

    If either input is zero, set lcm to zero.

  4. 4

    Otherwise divide a by g as long, multiply by b, and remove the sign.

Edge cases

Both zero

Enter 0 and 0

The explicit zero case avoids division by zero and gives 0.

One divides the other

Enter 6 and 18

The LCM is 18 because it is already a multiple of both.

What's going on

The least common multiple is the smallest positive number that both inputs divide exactly. For 12 and 18 it is 36. A student can use the idea to find when two repeating schedules will next line up, if they start together.

Scanner is the keyboard reader. The code first finds the GCD, which is the greatest common divisor, or largest shared factor. It uses the relation LCM = absolute value of (a / GCD) * b for non-zero inputs. Dividing before multiplying keeps the temporary product smaller.

A long variable stores the result so two int inputs have room for their product. Math.abs removes the sign from the result. The code treats an input zero as giving LCM zero and avoids division by a zero GCD. Do not use the original int product a * b for large values, because it can overflow before it is assigned to a wider variable.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is LCM of 12 and 18?

Pick an answer to check it.

Question 2

What must be checked before dividing by g?

Pick an answer to check it.

Questions people ask

Why divide before multiplying?

It reduces the intermediate value. The wider long calculation also prevents int product overflow.

Can negative inputs be used here?

Yes. The final absolute value makes the displayed LCM non-negative for int inputs.

Is LCM the same as the product?

Only when the two positive inputs have no shared factor greater than one.