Calculating the LCM of multiple numbers in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of numbers of any length and returns their LCM.

We will approach this problem in parts −

Part 1 − We will create a helper function to calculate the Greatest Common Divisor (GCD) of two numbers

Part 2 − Then using Part 1 helper function we will create another helper function to calculate the Least Common Multiple (LCM) of two numbers.

Part 3 − Finally, using Part 2 helper function we will create a function that loops over the array and calculates the array LCM.

Example

The code for this will be −

const calculateLCM = (...arr) => {
   const gcd2 = (a, b) => {
      // Greatest common divisor of 2 integers
      if(!b) return b===0 ? a : NaN;
         return gcd2(b, a%b);
   };
   const lcm2 = (a, b) => {
      // Least common multiple of 2 integers
      return a * b / gcd2(a, b);
   }
   // Least common multiple of a list of integers
   let n = 1;
   for(let i = 0; i < arr.length; ++i){
      n = lcm2(arr[i], n);
   }
   return n;
};
console.log(calculateLCM(12, 18, 7, 15, 20, 24, 28));

Output

And the output in the console will be −

2520
raja
Published on 20-Nov-2020 10:02:13
Advertisements