Exercise:
Write a Java Program to find the Lowest Common Multiple (LCM) of two numbers.
1.Calculate using While loop
Click Here to View the Solution!
public class LCMFinder {
public static void main(String[] args) {
int num1 = 60, num2 = 240, lcm;
// maximum number between n1 and n2 is stored in lcm
lcm = (num1 > num2) ? num1 : num2;
// Always true
while(true) {
if( lcm % num1 == 0 && lcm % num2 == 0 ) {
System.out.printf("The LCM of %d and %d is %d.", num1, num2, lcm);
break;
}
++lcm;
}
}
}
Click Here to View the Output!
The LCM of 60 and 240 is 240.
Click Here to View the Explanation!
- This program is used for finding the Lowest Common Multiple (LCM) of two numbers by using the while loop.
- Initially, two integer numbers
num1
andnum2
are initialized asnum1
= 60 andnum2 = 240
of which thelcm
needs to be found. - Since, the value of LCM must be greater or equal to the largest number, the initial value of the variable
lcm
is set to be the largest of the two numbersnum1
andnum2
. - For the
lcm
of two numbers, it should have zero remainder with both numbers. Therefore, in the infinite while loop, the value oflcm
is checked to find out whether it is exactly divisible by the two numbers. - If the
lcm
is found, the program can break out of the loop and print the output else, the value oflcm
is incremented, and thewhile loop
is run again. This is done until thelcm
is found. - In the end, the LCM is displayed on the screen.
2. CALCULATE USING GCD
Click Here to View the Solution!
public class LCMFinder {
public static void main(String[] args) {
int num1 = 60, num2 = 240, gcd = 1;
for(int i = 1; i <= num1 && i <= num2; ++i)
{
// Condition to check if i is factor of both numbers
if(num1 % i == 0 && num2 % i == 0)
gcd = i;
}
int lcm = (num1 * num2) / gcd;
System.out.printf("The LCM of %d and %d is %d.", num1, num2, lcm);
}
}
Click Here to View the Output!
The LCM of 60 and 240 is 240.
Click Here to View the Explanation!
- This program is used for finding the LCM of two numbers by using their GCD. It uses the while and for loop.
- Initially, two numbers,
num1
andnum2
are initialized asnum1 = 60
andnum2 = 240
of which the gcd and lcm is to be found. And another variable gcd is initialized asgcd = 1
. - The gcd of the two numbers is calculated through a condition set in the
for loop.
- After the gcd is found, the lcm of the two numbers is found using the following formula:
(num1 * num2) / gcd
. - As a result, the LCM of the given two numbers are displayed on the screen.