Java Program to Find LCM of Two Numbers

In this Java program, you’ll learn how to find LCM two numbers using the JAVA programming language.  

LCM (Least Common Multiple)- It is the least positive number that can be divided by two numbers.

How to Find LCM of two Numbers in JAVA? 

Example 1: using GCD 

RUN CODE SNIPPET
public class Main  
{ 
  public static void main(String[] args)  
  { 
    int n1 = 50, n2 = 390, gcd = 1; 
    for(int i = 1; i <= n1 && i <= n2; ++i) LCM 
    { 
      if(n1 % i == 0 && n2 % i == 0) 
        gcd = i; 
    } 
    int lcm = (n1 * n2) / gcd; 
    System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm); 
  } 
}

OUTPUT 

The LCM of 50 and 390 is 1950.

Example 2: using while loop 

RUN CODE SNIPPET
public class Main { 
  public static void main(String[] args)  
  { 
    int n1 = 9, n2 = 99, lcm; 
    lcm = (n1 > n2) ? n1 : n2; 
    while(true) { 
      if( lcm % n1 == 0 && lcm % n2 == 0 ) { 
        System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm); 
        break; 
      } 
      ++lcm; 
    } 
  } 
}

OUTPUT 

The LCM of 9 and 99 is 99.

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022