Description
You are given two integers n and t. Return the smallest number greater than or equal to n such that the product of its digits is divisible by t.
Example 1:
Input: n = 10, t = 2
Output: 10
Explanation:
The digit product of 10 is 0, which is divisible by 2, making it the smallest number greater than or equal to 10 that satisfies the condition.
Example 2:
Input: n = 15, t = 3
Output: 16
Explanation:
The digit product of 16 is 6, which is divisible by 3, making it the smallest number greater than or equal to 15 that satisfies the condition.
Constraints:
1 <= n <= 1001 <= t <= 10
Solutions
This function finds the smallest number greater than or equal to n whose product of digits is divisible by t. It computes the digit product with a loop that runs while num > 0, each time multiplying prod by the last digit (num % 10) and then dropping that digit with Math.floor(num / 10). If the finished product divides evenly by t (checked with prod % t === 0), the current n is the answer and gets returned; otherwise the function recursively calls itself with n + 1, repeating the same check on each successive number until it reaches the first one that satisfies the condition.
/**
* @param {number} n
* @param {number} t
* @return {number}
*/
var smallestNumber = function(n, t) {
let prod = 1;
let num = n;
while (num > 0) {
prod *= num % 10;
num = Math.floor(num / 10);
}
if (prod % t === 0) {
return n;
}
return smallestNumber(n + 1, t);
};