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
JavaScript - Find the smallest n digit number or greater
We are required to write a JavaScript function that takes in a number as the first argument, say n, and an array of numbers as the second argument. The function should return the smallest n digit number which is a multiple of all the elements specified in the array. If there exist no such n digit element then we should return the smallest such element.
For example: If the array is:
const arr = [12, 4, 5, 10, 9]
For both n = 2 and n = 3, the output should be 180
Example
Following is the code:
const arr = [12, 4, 5, 10, 9]
const num1 = 2;
const num2 = 3;
const allDivides = (arr, num) => arr.every(el => num % el === 0);
const smallestMultiple = (arr, num) => {
let smallestN = Math.pow(10, (num - 1));
while(!allDivides(arr, smallestN)){
smallestN++;
};
return smallestN;
};
console.log(smallestMultiple(arr, num1));
console.log(smallestMultiple(arr, num2));
Output
Following is the output in the console:
180 180
How It Works
The solution uses two helper functions:
-
allDivides()- checks if a number is divisible by all elements in the array -
smallestMultiple()- finds the smallest n-digit number that satisfies the condition
The algorithm starts from the smallest n-digit number (10^(n-1)) and increments until it finds a number divisible by all array elements.
Alternative Approach Using LCM
For better performance, we can calculate the LCM (Least Common Multiple) of all array elements first:
const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
const lcm = (a, b) => (a * b) / gcd(a, b);
const arrayLCM = arr => arr.reduce(lcm);
const optimizedSmallestMultiple = (arr, n) => {
const arrayLcm = arrayLCM(arr);
const minNDigit = Math.pow(10, n - 1);
if (arrayLcm >= minNDigit) {
return arrayLcm;
}
const multiplier = Math.ceil(minNDigit / arrayLcm);
return arrayLcm * multiplier;
};
const testArr = [12, 4, 5, 10, 9];
console.log(optimizedSmallestMultiple(testArr, 2));
console.log(optimizedSmallestMultiple(testArr, 3));
180 180
Conclusion
Both approaches solve the problem, but the LCM method is more efficient for large arrays. The key insight is finding the least common multiple and then ensuring it meets the n-digit requirement.
