English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to use Java programs to find the least common multiple of two numbers. This is done using for and while loops in Java.
The LCM of two integers is the smallest positive integer that can be completely divided by both numbers (without a remainder).
public class LCM { public static void main(String[] args) { int n1 = 72, n2 = 120, lcm; //n1and n2The maximum value between them is stored in lcm lcm = (n1 > n2) ? n1 : n2; // always true while(true) { if( lcm % n1 == 0 && lcm % n2 == 0 ) { System.out.printf("%d and %d are the least common multiple is %d.", n1, n2, lcm); break; } ++lcm; } } }
When running the program, the output is:
72 and12The latest common multiple of 0 is360.
In this program, the two numbers to find the least common multiple are stored in variables n1and n2.
Then, we first set lcm to the largest of the two numbers.
This is because the least common multiple cannot be less than the largest number. In an infinite while loop (while(true)), we check if lcm is completely divisible by n1and n2.
If so, we have found the least common multiple. We print the least common multiple and use the break statement to exit the while loop.
Otherwise, we will increase lcm by1and then retest 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, please checkJava program to find the GCD of two numbers.
public class LCM { public static void main(String[] args) { int n1 = 72, n2 = 120, gcd = 1; for(int i = 1; i <= n1 && i <= n2; ++i) { //Check if i is a factor of the two integers if(n1 % i == 0 && n2 % i == 0) gcd = i; } int lcm = (n1 * n2) / gcd; System.out.printf("%d and %d are the least common multiple is %d.", n1, n2, lcm); } }
The output of this program is consistent with the example1are the same.
In this case, within the for loop, we calculate the two numbers-n1and n2Calculate the GCD first, and then use the above formula to calculate the LCM.