Open In App

JavaScript Program to Find LCM

Given an array of integers, you need to find the LCM of the numbers present in the array in JavaScript. LCM is the least common multiple of all the elements of the array.

Example:



Input :-
arr = [3, 6, 9 , 12]
Output :-
The LCM of given array is :- 36
Explanation: 3*12 =36,
6*6=36,
9*4=36,
12*3=36
Hence 36 is the least common multiple of all the numbers of the array.

Approach 1: Computing GCD of numbers

An easy approach to solve the problem is to compute the GCD (greatest common divisor) of two numbers. Initialize a res variable to the first element of the array then iterate over the array and compute the GCD of the current element with the computed result so far then update the result by the product of res and current element divided by their GCD and then finally return res.

Example: Below is the implementation of this approach.






function LCM(arr) {
  function gcd(a, b) {
    if (b === 0) return a;
    return gcd(b, a % b);
  }
  
  let res = arr[0];
  
  for (let i = 1; i < arr.length; i++) {
    res = (res * arr[i]) / gcd(res, arr[i]);
  }
  
  return res;
}
  
let arr = [3, 6, 9, 12];
let res = LCM(arr);
console.log("The LCM of given array is: "+res);

Output
The LCM of given array is: 36

Approach 2:

Example:




function LCM(arr) {
  let max = Math.max(...arr);
  let multipleOfMax = [];
  
  for (let i = 1; i <= arr.reduce((a, b) => a * b); i++) {
    multipleOfMax.push(max * i);
  }
  
  for (let res of multipleOfMax) {
    if (arr.every(num => res % num === 0)) {
      return res;
    }
  }
}
  
let arr = [3,6,9,12];
let res = LCM(arr);
console.log("The LCM of given array is: "+res);

Output
The LCM of given array is: 36

Article Tags :