Count Beautiful Numbers - Problem

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: For number 144, digit product = 1×4×4 = 16, digit sum = 1+4+4 = 9. Since 16 % 9 ≠ 0, 144 is not beautiful.

Input & Output

Example 1 — Small Range
$ Input: l = 1, r = 10
Output: 10
💡 Note: All single digits 1-9 are beautiful (digit product equals digit sum), plus number 10 (product=0, sum=1, 0%1=0).
Example 2 — Including Zero Digits
$ Input: l = 10, r = 20
Output: 2
💡 Note: Numbers 10 and 20 are beautiful. 10: product=1×0=0, sum=1+0=1, 0%1=0. 20: product=2×0=0, sum=2+0=2, 0%2=0.
Example 3 — Larger Range
$ Input: l = 1, r = 100
Output: 19
💡 Note: Beautiful numbers include: all single digits 1-9, plus numbers with 0 digits where the remaining product is divisible by the sum (like 10, 20, 30, 40, 50, 60, 70, 80, 90, 100).

Constraints

  • 1 ≤ l ≤ r ≤ 1012
  • Both l and r are positive integers

Visualization

Tap to expand
Count Beautiful Numbers INPUT Range [l, r] 1 2 3 4 5 6 7 8 9 10 l=1 to r=10 l 1 r 10 Beautiful Number: product(digits) % sum(digits) == 0 Example: n=1 product=1, sum=1 1 % 1 = 0 (OK) ALGORITHM (DP) 1 Digit DP Setup Track sum & product of digits 2 State Definition dp[pos][sum][product][tight] 3 Count f(r) - f(l-1) Subtract to get range count 4 Check Condition prod % sum == 0 Checking Numbers 1-10 n sum prod prod%sum OK? 1 1 1 0 OK 2 2 2 0 OK ... ... ... ... ... 10 1 0 0 OK All single digits are beautiful! FINAL RESULT Beautiful numbers in [1,10]: 1 2 3 4 5 6 7 8 9 10 All 10 numbers are beautiful! Output 10 Count = 10 Beautiful numbers: 1-10 Key Insight: For single-digit numbers (1-9), the digit itself equals both the sum and product. Since any number divided by itself gives 0 remainder, all single digits are beautiful. For 10: sum=1, product=0. 0 % 1 = 0, so 10 is also beautiful. Digit DP handles larger ranges efficiently. TutorialsPoint - Count Beautiful Numbers | DP Approach
Asked in
Google 15 Microsoft 12 Amazon 8
25.0K Views
Medium Frequency
~35 min Avg. Time
890 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