Open In App

JavaScript Program to Find LCM

Last Updated : 18 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Javascript




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:

  • Find the maximum number of the array
  • Now create an empty array that will consist of all the multiples of the maximum numbers up to the product of all numbers of the array, use reduce method of the array for this purpose and push the result of each iteration on the new array.
  • Check in that array if a value is the multiple of all the numbers of the input array. The first entry of that array is the LCM of all the numbers.

Example:

Javascript




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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads