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 - Optimal Solution INPUT Find nth number divisible by a, b, or c a=2 2,4,6,8... b=3 3,6,9,12... c=5 5,10,15... Ugly Numbers (Union): 2 3 4 5 6 8 n=3 n = 3 a = 2, b = 3, c = 5 Find 3rd ugly number divisible by 2, 3, or 5 ALGORITHM STEPS 1 Binary Search Setup lo=1, hi=2*10^9 2 Count Function Use Inclusion-Exclusion count(m) = m/a + m/b + m/c - m/lcm(a,b) - m/lcm(b,c) - m/lcm(a,c) + m/lcm(a,b,c) 3 Binary Search Loop mid = (lo + hi) / 2 if count(mid) >= n: hi = mid, else: lo = mid+1 4 Return Result lo = nth ugly number FINAL RESULT Binary Search Trace: mid=4: count(4)=3 OK 4/2=2, 4/3=1, 4/5=0 -4/6=0, -4/10=0, -4/15=0 +4/30=0 = 3 count(4)=3 >= n=3 Found: lo = 4 OUTPUT 4 Verification: Ugly nums: 2, 3, 4, 5, 6... 3rd ugly number = 4 Key Insight: Use Binary Search + Inclusion-Exclusion Principle. For any number m, count how many ugly numbers exist <= m using: |A union B union C| = |A|+|B|+|C| - |A∩B| - |B∩C| - |A∩C| + |A∩B∩C| Time: O(log(2*10^9)), Space: O(1). LCM handles intersections for divisibility counting. TutorialsPoint - Ugly Number III | Binary Search + Inclusion-Exclusion
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