Algorithm
-
nput: Accept two numbers as input.
-
Find the greater number: Determine the larger of the two input numbers.
-
Initialize variables: Set
lcm
to the greater number. -
Loop until found: Start a loop that continues until you find the LCM.
- Inside the loop, check if both input numbers are divisible by the current value of
lcm
. - If they are, break out of the loop as you have found the LCM.
- If not, increment
lcm
by the value of the greater number.
- Inside the loop, check if both input numbers are divisible by the current value of
-
Output: Print or return the final value of
lcm
as the result.
Code Examples
#1 Code Example- LCM Using while Loop and if Statement
Code -
Javascript Programming
// program to find the LCM of two integers
// take input
const num1 = prompt('Enter a first positive integer: ');
const num2 = prompt('Enter a second positive integer: ');
// higher number among number1 and number2 is stored in min
let min = (num1 > num2) ? num1 : num2;
// while loop
while (true) {
if (min % num1 == 0 && min % num2 == 0) {
console.log(`The LCM of ${num1} and ${num2} is ${min}`);
break;
}
min++;
}
Copy The Code &
Try With Live Editor
Output
Enter a second positive integer: 8
The LCM of 6 and 8 is 24
#2 Code Example- LCM Calculation Using HCF
Code -
Javascript Programming
// program to find the LCM of two integers
let hcf;
// take input
const number1 = prompt('Enter a first positive integer: ');
const number2 = prompt('Enter a second positive integer: ');
// looping from 1 to number1 and number2 to find HCF
for (let i = 1; i < = number1 && i <= number2; i++) {
// check if is factor of both integers
if( number1 % i == 0 && number2 % i == 0) {
hcf = i;
}
}
// find LCM
let lcm = (number1 * number2) / hcf;
// display the hcf
console.log(`HCF of ${number1} and ${number2} is ${lcm}.`);
Copy The Code &
Try With Live Editor
Output
Enter a second positive integer: 8
The LCM of 6 and 8 is 24.
Demonstration
JavaScript Programing Example to Find LCM-DevsEnv