Ugly Number III
Solution Code
from math import lcm
class Solution:
def nthUglyNumber(self, n: int, a: int, b: int, c: int) -> int:
# Precompute four LCMs so each evaluation of f(x) takes O(1) time.
lab = lcm(a, b)
lac = lcm(a, c)
lbc = lcm(b, c)
labc = lcm(lab, c)
# Inclusion-exclusion: count the ugly numbers in [1, x].
def count_ugly(x: int) -> int:
return (
x // a + x // b + x // c
- x // lab - x // lac - x // lbc
+ x // labc
)
# Binary search for the smallest x with f(x) >= n.
lo, hi = 1, 2_000_000_000
while lo < hi:
mid = lo + (hi - lo) // 2
if count_ugly(mid) >= n:
hi = mid
else:
lo = mid + 1
return loTime Complexity
O(log V + log C)
Space Complexity
O(1)

