Write a program to calculate the least common multiple of two numbers JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a function that accepts two numbers and returns their least common multiple.

Least Common Multiple (LCM)

The least common multiple of two numbers a and b is the smallest positive integer that is divisible by both a and b.

For example − The LCM of 6 and 8 is 24 because 24 is the smallest positive integer that is divided by both 6 and 8.

Method to calculate LCM

One of the many ways of calculating LCM of two numbers a and b is by dividing the product of a and b by the greatest integer (also known as greatest common divisor or GCD) that divides both a and b.

In case of 6 and 8, their product is 48 and the greatest integer that divides them both is 2 so their LCM is −

(6*8)/2 = 24

Having these things clear, now let’s move to the coding part −

Example

const lcm = (a, b) => {
   let min = Math.min(a, b);
   while(min >= 2){
      if(a % min === 0 && b % min === 0){
         return (a*b)/min;
      };
      min--;
   };
   return (a*b);
};
console.log(lcm(6, 8));
console.log(lcm(16, 18));
console.log(lcm(0, 8));
console.log(lcm(11, 28));
console.log(lcm(18, 34));

Understanding the code

Since the greatest integer that exactly divides both the numbers will still be smaller or equal to the smaller of the two numbers, we are calculating LCM for, we run a decrementing loop from the smaller number all the way down to 2.

If in our iterations we find any number that divides both the numbers we can guarantee that it’s the largest number that divides them both because we are in a decrementing loop, so we return right there with the LCM.

If we iterate through the complete it means that we didn’t found any such number and 1 is the only number that divides them both (in other terms the numbers are co-prime), so we simply return their product.

Output

The output in the console will be −

24
144
0
308
306
raja
Published on 25-Aug-2020 06:45:54
Advertisements