Ugly Number III - Problem
An ugly number is a positive integer that is divisible by a, b, or c.
Given four integers n, a, b, and c, return the nth ugly number.
Example: If a = 2, b = 3, c = 5, and n = 4, the ugly numbers are: 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ... The 4th ugly number is 5.
Input & Output
Example 1 — Basic Case
$
Input:
n = 3, a = 2, b = 3, c = 5
›
Output:
4
💡 Note:
Ugly numbers divisible by 2, 3, or 5: {2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...}. The 3rd ugly number is 4.
Example 2 — Larger Case
$
Input:
n = 4, a = 2, b = 3, c = 4
›
Output:
6
💡 Note:
Ugly numbers: {2, 3, 4, 6, 8, 9, 10, 12, ...}. The 4th ugly number is 6.
Example 3 — Single Divisor
$
Input:
n = 1000000000, a = 2, b = 217983653, c = 336916467
›
Output:
1999999984
💡 Note:
For very large n, the binary search approach efficiently finds the billionth ugly number.
Constraints
- 1 ≤ n, a, b, c ≤ 109
- 1 ≤ a * b * c ≤ 1018
- It's guaranteed that the result will be in range [1, 2 * 109]
Visualization
Tap to expand
Understanding the Visualization
1
Input
n=4, a=2, b=3, c=5 (find 4th ugly number)
2
Process
Count numbers divisible by 2, 3, or 5
3
Output
4th ugly number is 5
Key Takeaway
🎯 Key Insight: Use binary search with inclusion-exclusion to count ugly numbers efficiently without generating them
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code