LCM using while Loop and if Statement
public class Main {
public static void main(String[] args) {
int n1 = 72, n2 = 120, lcm;
// maximum number between n1 and n2 is stored in lcm
lcm = (n1 > n2) ? n1 : n2;
// Always true
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;
}
}
}
The LCM of 72 and 120 is 360.
This Java program calculates the Least Common Multiple (LCM) of two numbers using a while loop.
Here's a breakdown of how the code works:
Initialization:
n1 and n2 are initialized with values 72 and 120 respectively.lcm is initialized without a value.Finding the Maximum:
n1 and n2 using the ternary operator (? :) and assigns the maximum of the two numbers to the variable lcm.lcm initially holds the larger of the two numbers.Calculating the LCM:
while loop with the condition true, indicating an infinite loop.lcm is divisible by both n1 and n2 using the modulo operator (%).lcm is divisible by both n1 and n2, it prints the LCM using the printf method and breaks out of the loop.lcm is not divisible by both n1 and n2, it increments lcm by 1 and continues the loop.Output:
n1 and n2 using the printf method.In summary, this program calculates the LCM of two given numbers (n1 and n2) using a while loop and prints the result. It starts with the larger of the two numbers as the initial guess for the LCM and increments it until it finds a number that is divisible by both n1 and n2.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.