
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Smallest Common Multiple of an Array of Numbers in JavaScript
Suppose, we have an array of two numbers that specify a range. We are required to write a function that finds the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters.
The range will be an array of two numbers that will not necessarily be in numerical order.
For example, if given [1, 3], then we are required to find the smallest common multiple of both 1 and 3 that is also evenly divisible by all numbers between 1 and 3. The answer here would be 6.
Example
The code for this will be −
const range = [1, 12]; const smallestCommon = (array = []) => { arr = array.slice().sort((a, b) => a − b); let result = []; for(let i = arr[0]; i <= arr[1]; i++){ result.push(i); }; let i = 1; let res; while(result.every(item=>res%item==0)==false){ i++; res = arr[1]*i; } return res; } console.log(smallestCommon(range));
Output
And the output in the console will be −
27720
Advertisements