Ugly Number III - Problem
An ugly number is a positive integer that is divisible by at least one of three given numbers: a, b, or c.
Given four integers n, a, b, and c, your task is to find the n-th ugly number in the sequence of all ugly numbers sorted in ascending order.
Example: If a = 2, b = 3, c = 5, then the ugly numbers are: 2, 3, 4, 5, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20...
The challenge is to find this efficiently for large values of n (up to 2 ร 109), making a brute force approach impractical.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 3, a = 2, b = 3, c = 5
โบ
Output:
4
๐ก Note:
The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10, 12... The 3rd ugly number is 4.
example_2.py โ Larger Input
$
Input:
n = 4, a = 2, b = 3, c = 4
โบ
Output:
6
๐ก Note:
Since 4 = 2ร2, numbers divisible by 4 are also divisible by 2. The ugly numbers are 2, 3, 4, 6, 8, 9... The 4th ugly number is 6.
example_3.py โ Edge Case
$
Input:
n = 1000000000, a = 2, b = 217983653, c = 336916467
โบ
Output:
1999999984
๐ก Note:
This demonstrates why we need an efficient algorithm - brute force would be impossible for such large n.
Visualization
Tap to expand
Understanding the Visualization
1
Binary Search Setup
Search space is from 1 to n ร min(a,b,c) since the n-th ugly number can't exceed this
2
Counting Function
For any value x, count ugly numbers โค x using inclusion-exclusion principle
3
Include Individual Sets
Add โx/aโ + โx/bโ + โx/cโ to count multiples of each
4
Exclude Intersections
Subtract โx/lcm(a,b)โ + โx/lcm(a,c)โ + โx/lcm(b,c)โ to avoid double counting
5
Include Triple Intersection
Add back โx/lcm(a,b,c)โ for numbers divisible by all three
Key Takeaway
๐ฏ Key Insight: Instead of generating ugly numbers sequentially (slow), we binary search on the answer and use inclusion-exclusion principle to count ugly numbers โค any value in constant time, achieving O(log n) complexity.
Time & Space Complexity
Time Complexity
O(n ร result)
We potentially check every number up to the n-th ugly number, which could be very large
โ Linear Growth
Space Complexity
O(1)
Only using a few variables to track count and current number
โ Linear Space
Constraints
- 1 โค n โค 2 ร 109
- 2 โค a, b, c โค 109
- Important: The result will fit in a 32-bit signed integer
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code