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: 1
💡 Note: Only number 1 is beautiful: digit product = 1, digit sum = 1, and 1 % 1 = 0. Numbers 2-10 don't satisfy the condition.
Example 2 — Including Zero Digits
$ Input: l = 10, r = 20
Output: 1
💡 Note: Number 10: product = 1×0 = 0, sum = 1+0 = 1, and 0 % 1 = 0, so it's beautiful. Other numbers in range don't satisfy the condition.
Example 3 — Larger Range
$ Input: l = 1, r = 100
Output: 4
💡 Note: Beautiful numbers are: 1 (1%1=0), 10 (0%1=0), 20 (0%2=0), 100 (0%1=0). All have zero in product making them divisible by their digit sum.

Constraints

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

Visualization

Tap to expand
Beautiful Numbers: Product % Sum = 0Number: 132Product: 1×3×2 = 6Sum: 1+3+2 = 66 % 6 = 0 ✓Number: 144Product: 1×4×4 = 16Sum: 1+4+4 = 916 % 9 ≠ 0 ✗Special Case: Numbers with 0 digit → Product = 0 → Always beautiful!10: 0%1=0 ✓20: 0%2=0 ✓Count all beautiful numbers in range [l, r]
Understanding the Visualization
1
Input Range
Given range [l, r] to check for beautiful numbers
2
Check Beautiful
For each number: product of digits divisible by sum of digits
3
Count Result
Return total count of beautiful numbers in range
Key Takeaway
🎯 Key Insight: Numbers with zero digits are automatically beautiful since their product is 0, and 0 is divisible by any non-zero sum
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