Smallest Divisible Digit Product I - Problem

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.

For example, if n = 15 and t = 3, we need to find the smallest number ≥ 15 where the product of digits is divisible by 3. The number 16 has digit product 1×6 = 6, which is divisible by 3, so the answer is 16.

Input & Output

Example 1 — Basic Case
$ Input: n = 15, t = 3
Output: 16
💡 Note: Starting from 15: digit product = 1×5 = 5, not divisible by 3. Next number 16: digit product = 1×6 = 6, which is divisible by 3, so return 16.
Example 2 — Zero Digit
$ Input: n = 19, t = 7
Output: 20
💡 Note: Starting from 19: digit product = 1×9 = 9, not divisible by 7. Next number 20: digit product = 2×0 = 0, which is divisible by 7, so return 20.
Example 3 — Answer is n itself
$ Input: n = 12, t = 2
Output: 12
💡 Note: Starting from 12: digit product = 1×2 = 2, which is divisible by 2, so return 12 itself.

Constraints

  • 1 ≤ n ≤ 106
  • 1 ≤ t ≤ 106

Visualization

Tap to expand
Smallest Divisible Digit Product I Early Termination Optimization INPUT n 15 t 3 Search Space 15 16 17 18 ... Digit Products 15: 1 x 5 = 5 16: 1 x 6 = 6 17: 1 x 7 = 7 18: 1 x 8 = 8 5 % 3 != 0 6 % 3 = 0 - - ALGORITHM STEPS 1 Initialize Start from num = n 2 Calculate Product Multiply all digits 3 Check Divisibility If product % t == 0 4 Return or Continue Found: return num Else: num++, go to 2 num = 15 num = 16 OK - Found! loop FINAL RESULT Output 16 Verification Number: 16 Digits: 1, 6 Product: 1 x 6 = 6 6 % 3 = 0 OK Smallest Valid 16 is the first num >= 15 with product % 3 = 0 Key Insight: Early Termination: Stop as soon as we find a valid number. Linear search from n is efficient because valid numbers occur frequently. Digit product calculation is O(log n) per number. TutorialsPoint - Smallest Divisible Digit Product I | Early Termination Optimization
Asked in
Google 25 Microsoft 15
12.0K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen