Java Program to Find LCM of two Numbers

In this program we will look at two methods of finding LCM of two numbers 1. by using GDC and 2. without using GDC

Also, you should know what is LCM- LCM stands for Lowest common multiple. LCM of two integers is the smallest positive integer which perfectly divides both the numbers.

Method 1: LCM using while loop and if statements

public class LCMOfTwoNumbers{
  public static void main(String[] args) {

    int num1 = 72, num2 = 120, lcm;

    // maximum number between num1 and num2 is stored in lcm
    lcm = (num1 > num2) ? num1 : num2;

    // Always true
    while(true) {
      if( lcm % num1 == 0 && lcm % num2 == 0 ) {
        System.out.printf("The LCM of %d and %d is %d.", num1, num2, lcm);
        break;
      }
      ++lcm;
    }
  }
}

Output

The LCM of 72 and 120 is 360.

In this program, the two numbers whose LCD is to be calculated is stored in two variables num1 and num2.

then, we initially set the LCS of the two numbers as the largest of the two numbers as LCM of two numbers can not be greater the largest number.

And inside the while loop we check if LCM perfectly divides both num1 and num2 or not.

If It finds the perfectly divisible number, it prints the LCM and breaks the loop. if Condition is not satisfied, we increment the LCM by 1 and retest divisibility condition.

Method 2: LCD Using GDC

We can also find the LCM of two numbers using GDC and the formula is

LCM = (n1 * n2) / GCD

If you don’t know how to find GDC, you can refer Java Program to Find GCD of two Numbers

public class LCDUsingGDC{
  public static void main(String[] args) {

    int num1 = 72, num2 = 120, lcm;

    // maximum number between num1 and num2 is stored in lcm
    lcm = (num1 > num2) ? num1 : num2;

    // Always true
    while(true) {
      if( lcm % num1 == 0 && lcm % num2 == 0 ) {
        System.out.printf("The LCM of %d and %d is %d.", num1, num2, lcm);
        break;
      }
      ++lcm;
    }
  }
}

Output

The LCM of 72 and 120 is 360.

Leave a Reply