Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding the least common multiple of a range of numbers in JavaScript?
We are required to write a JavaScript function that takes in an array of exactly two numbers specifying a range.
The function should then calculate the least common multiple of all the numbers within that range and return the final result.
Understanding LCM and GCD
To find the LCM of multiple numbers, we first need helper functions for GCD (Greatest Common Divisor) and LCM of two numbers:
- GCD: The largest number that divides both numbers evenly
- LCM: The smallest positive number that is divisible by both numbers
- Formula: LCM(a, b) = (a × b) / GCD(a, b)
Implementation
const range = [8, 3];
const gcd = (a, b) => {
return !b ? a : gcd(b, a % b);
}
const lcm = (a, b) => {
return a * (b / gcd(a, b));
};
const rangeLCM = (arr = []) => {
if (arr[0] > arr[1]) arr = [arr[1], arr[0]];
let result = arr[0];
for (let x = arr[0]; x
840
How It Works
Let's trace through the example with range [8, 3]:
- First, swap to [3, 8] since 8 > 3
- Start with result = 3
- LCM(3, 3) = 3
- LCM(3, 4) = 12
- LCM(12, 5) = 60
- LCM(60, 6) = 60
- LCM(60, 7) = 420
- LCM(420, 8) = 840
Step-by-Step Example
// Let's see the process step by step
const rangeWithSteps = (arr = []) => {
if (arr[0] > arr[1]) arr = [arr[1], arr[0]];
let result = arr[0];
console.log(`Starting with: ${result}`);
for (let x = arr[0]; x
Starting with: 5
LCM(5, 5) = 5
LCM(5, 6) = 30
LCM(30, 7) = 210
LCM(210, 8) = 840
Final result: 840
Alternative Approach with Validation
const rangeLCMValidated = (arr) => {
// Input validation
if (!Array.isArray(arr) || arr.length !== 2) {
throw new Error("Input must be an array of exactly 2 numbers");
}
const [start, end] = arr[0]
60
660
Conclusion
Finding the LCM of a range requires iteratively calculating the LCM of each number with the running result. The key is using the mathematical relationship between GCD and LCM to efficiently compute the result.
Advertisements
