Algorithm


  1. nput: Accept two numbers as input.

  2. Find the greater number: Determine the larger of the two input numbers.

  3. Initialize variables: Set lcm to the greater number.

  4. 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.
  5. 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

x
+
cmd
Enter a first positive integer: 6
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

x
+
cmd
Enter a first positive integer: 6
Enter a second positive integer: 8
The LCM of 6 and 8 is 24.
Advertisements

Demonstration


JavaScript Programing Example to Find LCM-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way