- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Example
The code for this will be −
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]]); for(let x = result = arr[0]; x <= arr[1]; x++) { result = lcm(x, result); } return result; } console.log(rangeLCM(range));
Output
And the output in the console will be −
840
Advertisements