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 SNIPPETpublic 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 SNIPPETpublic 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.