

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculating the LCM of multiple numbers in JavaScript
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
- Related Questions & Answers
- Find LCM of two numbers
- Calculating 1s in binary representation of numbers in JavaScript
- Calculating variance for an array of numbers in JavaScript
- LCM of an array of numbers in Java
- Java program to find the LCM of two numbers
- GCD and LCM of two numbers in Java
- Calculating the sum of digits of factorial JavaScript
- Calculating the weight of a string in JavaScript
- Java Program to Find LCM of two Numbers
- C++ Program to Find the GCD and LCM of n Numbers
- Finding the least common multiple of a range of numbers in JavaScript?
- Program to find LCM of two Fibonnaci Numbers in C++
- Smallest Common Multiple of an array of numbers in JavaScript
- Calculating resistance of n devices - JavaScript
- Calculating median of an array JavaScript
Advertisements