Unlocking the Secrets of Least Common Multiples

The Basics of LCM

Simply put, the Least Common Multiple (LCM) is the smallest positive integer that is perfectly divisible by two given integers. For instance, the LCM of 6 and 8 is 24.

Using Loops and Conditional Statements

In our first example, we’ll utilize a while loop and if statement to find the LCM. The program prompts the user to input two positive integers, and the greater number is stored in a variable called min. Since the LCM cannot be less than the greater number, we use a while loop to iterate until we find the solution.


let num1 = parseInt(prompt("Enter the first number: "));
let num2 = parseInt(prompt("Enter the second number: "));
let min = Math.max(num1, num2);

while (true) {
  if (min % num1 == 0 && min % num2 == 0) {
    console.log(`The LCM of ${num1} and ${num2} is ${min}`);
    break;
  }
  min++;
}

In each iteration, we divide min by both num1 and num2. If both remainders are equal to 0, we’ve found the LCM, and the program terminates. If not, we increment min by 1 and continue the loop.

The Formula Approach

We can also find the LCM using a formula that involves the Highest Common Factor (HCF). To calculate the HCF, you can refer to our JavaScript program on finding HCF.

In our second example, we’ll use this formula to find the LCM. Here’s how it works:

  • First, we calculate the HCF of the two numbers.
  • Then, we plug the HCF into the formula to find the LCM: LCM = (num1 * num2) / HCF.

function findHCF(num1, num2) {
  // implementation of HCF calculation
}

let num1 = parseInt(prompt("Enter the first number: "));
let num2 = parseInt(prompt("Enter the second number: "));
let hcf = findHCF(num1, num2);
let lcm = (num1 * num2) / hcf;

console.log(`The LCM of ${num1} and ${num2} is ${lcm}`);

By mastering these two approaches, you’ll be well-equipped to tackle even the most challenging LCM problems.

Leave a Reply