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
Ugly Number III: Find 4th number divisible by 2, 3, or 5Numbers:12345678Count:1st2nd3rd4th ✓5th6thCheck:2%2=03%3=04%2=05%5=06%2=08%2=0Ugly numbers: 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...4th ugly number = 5
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
Asked in
Google 15 Facebook 12 Amazon 8
28.5K 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