Skip to content

3345. Smallest Divisible Digit Product I

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 <= 100
  • 1 <= t <= 10

 

Solutions

Solution: Math

  • Time complexity: O(1)
  • Space complexity: O(1)

 

JavaScript

js
/**
 * @param {number} n
 * @param {number} t
 * @return {number}
 */
const smallestNumber = function (n, t) {
  let current = n;
  let product = 1;

  while (current) {
    product *= current % 10;
    current = Math.floor(current / 10);
  }

  if (product % t === 0) return n;

  const base = Math.floor(n / 10) * 10;
  const lastDigit = n % 10;

  for (let num = lastDigit + 1; num <= 9; num++) {
    product = (product / (num - 1)) * num;

    if (product % t === 0) {
      return base + num;
    }
  }

  return base + 10;
};

Released under the MIT license