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

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024