Ugly Number III Problem
Description
LeetCode Problem 1201.
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 n^th ugly number.
Example 1:
Input: n = 3, a = 2, b = 3, c = 5
Output: 4
Explanation: The ugly numbers are 2, 3, 4, 5, 6, 8, 9, 10... The 3^rd is 4.
Example 2:
Input: n = 4, a = 2, b = 3, c = 4
Output: 6
Explanation: The ugly numbers are 2, 3, 4, 6, 8, 9, 10, 12... The 4^th is 6.
Example 3:
Input: n = 5, a = 2, b = 11, c = 13
Output: 10
Explanation: The ugly numbers are 2, 4, 6, 8, 10, 11, 12, 13... The 5^th is 10.
Constraints:
1 <= n, a, b, c <= 10^91 <= a * b * c <= 10^18- It is guaranteed that the result will be in range
[1, 2 * 10^9].
Solution
Approach: Binary Search on the Answer + Inclusion-Exclusion
n can be 10^9, so listing ugly numbers one by one is too slow. Turn the question around: let count(x) be the number of ugly numbers in 1..x. It never decreases as x grows, so the n-th ugly number is the smallest x with count(x) >= n, which binary search finds.
count(x) takes O(1) with inclusion-exclusion. There are x / a multiples of a up to x (integer division), and similarly for b and c. Numbers divisible by two of them were counted twice, so subtract the multiples of lcm(a, b), lcm(a, c) and lcm(b, c). Numbers divisible by all three were added three times and subtracted three times, so add the multiples of lcm(a, b, c) back:
count(x) = x/a + x/b + x/c - x/lcm(a,b) - x/lcm(a,c) - x/lcm(b,c) + x/lcm(a,b,c)
The answer is guaranteed to be at most 2 * 10^9, so search x in [1, 2 * 10^9]. The smallest x with count(x) >= n is itself an ugly number: count only goes up at ugly numbers.
The tricky part is overflow. lcm(a, b, c) can be as large as a * b * c <= 10^18, so use 64-bit integers, and compute lcm(x, y) as x / gcd(x, y) * y (divide first). JavaScript numbers are exact only up to 2^53. But an lcm larger than 2 * 10^9 divides no candidate, so the JavaScript code caps it just above that limit.
Complexity: O(log(2 · 109)), about 31 steps, plus the gcds. O(1) space.
from math import gcd
class Solution:
def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
def lcm(x: int, y: int) -> int:
return x // gcd(x, y) * y
ab, ac, bc = lcm(a, b), lcm(a, c), lcm(b, c)
abc = lcm(ab, c)
def count(x: int) -> int:
# How many numbers in 1..x are divisible by a, b or c (inclusion-exclusion).
return x // a + x // b + x // c - x // ab - x // ac - x // bc + x // abc
lo, hi = 1, 2 * 10**9 # the answer is guaranteed to be at most 2 * 10^9
while lo < hi:
mid = (lo + hi) // 2
if count(mid) >= n:
hi = mid
else:
lo = mid + 1
return lo