Function to calculate the least common multiple of two numbers in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

The least common multiple, (LCM) of two integers a and b, is the smallest positive integer that is divisible by both a and b.

For example −

LCM of 4 and 6 is 12 because 12 is the smallest number that is exactly divisible by both 4 and 6.

We are required to write a JavaScript function that takes in two numbers, computes and returns the LCM of those numbers.

Example

Following is the code −

const num1 = 4;
const num2 = 6;
const findLCM = (num1, num2) => {
   let hcf;
   for (let i = 1; i <= num1 && i <= num2; i++) {
      if( num1 % i == 0 && num2 % i == 0) {
         hcf = i;
      };
   };
   let lcm = (num1 * num2) / hcf;
   return lcm;
};
console.log(findLCM(num1, num2));

Output

Following is the output on console −

12
raja
Published on 11-Dec-2020 08:52:30
Advertisements