- 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
Calculating least common of a range JavaScript
We are required to write a function that takes in an array of two numbers a and b (a >= b) and returns the least common multiple of all the numbers between [a, b].
Approach
We will first write a basic function that calculates the least common multiple of two numbers, once we have that we will recursively call it over the numbers that fall between [a, b] and finally return the result.
Example
const lcm = (a, b) => { let min = Math.min(a, b); while(min >= 2){ if(a % min === 0 && b % min === 0){ return (a*b)/min; }; min--; }; return (a*b); }; const leastCommonMultipleInRange = (arr, len = arr[0], res = 1) => { if(len <= arr[1]){ return leastCommonMultipleInRange(arr, len+1, lcm(res, len)); }; return res; }; console.log(leastCommonMultipleInRange([6, 8])); console.log(leastCommonMultipleInRange([6, 18])); console.log(leastCommonMultipleInRange([1, 8])); console.log(leastCommonMultipleInRange([10, 25]));
Output
The output in the console will be −
168 12252240 840 26771144400
Advertisements