Java Program to Find LCM of two Numbers

To understand this example, you should have the knowledge of the following Java programming topics:


The LCM of two integers is the smallest positive integer that is perfectly divisible by both the numbers (without a remainder).

Example 1: LCM using while Loop and if Statement

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    int n1 = 72, n2 = 120;

    int gcd = findGCD(n1, n2);
    int lcm = (n1 * n2) / gcd;

    System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
  }

  public static int findGCD(int a, int b) {
    if (b == 0)
      return a;
    return findGCD(b, a % b);
  }
}

Output

The LCM of 72 and 120 is 360.

In this program, the two numbers whose LCM is to be found are stored in variables n1 and n2 respectively.

Then, we initially set lcm to the largest of the two numbers. This is because, LCM cannot be less than the largest number.

Inside the infinite while loop (while(true)), we check if lcm perfectly divides both n1 and n2 or not.

If it does, we've found the LCM. We print the LCM and break out from the while loop using break statement.

Else, we increment lcm by 1 and re-test the divisibility condition.


We can also use GCD to find the LCM of two numbers using the following formula:

LCM = (n1 * n2) / GCD

If you don't know how to calculate GCD in Java, check Java Program to find GCD of two numbers.

Example 2: Calculate LCM using GCD

public class Main {
  public static void main(String[] args) {
    int n1 = 72, n2 = 120;

    int gcd = findGCD(n1, n2);
    int lcm = (n1 * n2) / gcd;

    System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
  }

  public static int findGCD(int a, int b) {
    if (b == 0)
      return a;
    return findGCD(b, a % b);
  }
}

The output of this program is the same as Example 1.

Here, inside the for loop, we calculate the GCD of the two numbers - n1 and n2. After the calculation, we use the above formula to calculate the LCM.

Before we wrap up, let’s put your knowledge of Java Program to Find LCM of two Numbers to the test! Can you solve the following challenge?

Challenge:

Write a function to calculate the LCM of two numbers.

  • The Least Common Multiple (LCM) of two numbers is the smallest multiple that is divisible by both numbers.
  • For example, the LCM of 4 and 6 is 12 because 12 is the smallest number that both 4 and 6 can divide evenly.
  • Return the LCM of the input num1 and num2.
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges