Problem Description
Given four integers n, a, b, and c, an ugly number is defined as a positive integer that is divisible by at least one of a, b, or c. The task is to find the nth ugly number.
Key Insights
- Use binary search on the answer space (from 1 to an upper bound like n * min(a, b, c)) to efficiently locate the nth ugly number.
- Compute the count of ugly numbers ≤ x using the inclusion-exclusion principle.
- Leverage the formula: count(x) = ⌊x/a⌋ + ⌊x/b⌋ + ⌊x/c⌋ - ⌊x/lcm(a, b)⌋ - ⌊x/lcm(b, c)⌋ - ⌊x/lcm(a, c)⌋ + ⌊x/lcm(a, b, c)⌋.
- Calculate least common multiples (lcm) using the greatest common divisor (gcd).
Space and Time Complexity
Time Complexity: O(log(max_value)) where max_value is around n * min(a, b, c). Each binary search step does constant time operations. Space Complexity: O(1)
Solution
We perform binary search on the range of potential ugly numbers. For any guess x, the count of numbers ≤ x that are divisible by a, b, or c is obtained via the inclusion-exclusion principle. The gcd and lcm functions are used to count the numbers divisible by the pairs and triplet of divisors. Adjust the binary search window based on whether the count is less than or at least n until the exact nth ugly number is found.