Count Beautiful Numbers Problem
Description
LeetCode Problem 3490.
You are given two positive integers, l and r. A positive integer is called beautiful if the product of its digits is divisible by the sum of its digits.
Return the count of beautiful numbers between l and r, inclusive.
Example 1:
Input: l = 10, r = 20
Output: 2
Explanation:
The beautiful numbers in the range are 10 and 20.
Example 2:
Input: l = 1, r = 15
Output: 10
Explanation:
The beautiful numbers in the range are 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10.
Constraints:
1 <= l <= r < 10^9
Solution
Approach: Digit DP with Memoization
Let count(x) be the number of beautiful numbers in [1, x]; the answer is count(r) - count(l - 1).
Define f(rem, s, prod): the number of ways to append rem more digits to a prefix whose digit sum is s and digit product is prod, so that the final product is divisible by the final digit sum.
- If
prod == 0, any digits work (zero is divisible by every positive sum), so the result is10^rem. - If
rem == 0, the result is 1 whenprod % s == 0, else 0. - Otherwise try the next digit:
0leads to the zero product case, and digits1to9recurse withs + dandprod * d.
Results are memoized on (rem, s, prod); only a few products are reachable, since they are made of the factors 2, 3, 5 and 7.
To compute count(x), add f(len - 1, d, d) for each shorter length and each leading digit 1..9. For the same length, walk along the digits of x: at each position, add f(...) for every smaller digit than the one in x (the first digit starts at 1), then follow the digit of x. Finally add 1 if x itself is beautiful.
Complexity: About O(D * S * P * 10) time and space, where D = 9 is the number of digits, S <= 81 is the digit sum and P is the number of distinct reachable products (a few thousand).
from functools import lru_cache
class Solution:
def beautifulNumbers(self, l: int, r: int) -> int:
@lru_cache(None)
def f(rem: int, s: int, prod: int) -> int:
# ways to append rem digits so that the final product is divisible by the final digit sum
if prod == 0:
return 10 ** rem
if rem == 0:
return 1 if prod % s == 0 else 0
res = 10 ** (rem - 1) # next digit 0
for d in range(1, 10):
res += f(rem - 1, s + d, prod * d)
return res
def count(x: int) -> int:
# beautiful numbers in [1, x]
if x <= 0:
return 0
digits = list(map(int, str(x)))
m = len(digits)
res = 0
for length in range(1, m):
for d in range(1, 10):
res += f(length - 1, d, d)
s, prod = 0, 1
for i, c in enumerate(digits):
for d in range(1 if i == 0 else 0, c):
res += f(m - i - 1, s + d, prod * d)
s += c
prod *= c
if prod % s == 0:
res += 1
return res
return count(r) - count(l - 1)