classSolution: defnthUglyNumber(self, n: int, a: int, b: int, c: int) -> int: defcheck(x: int) -> bool: cnt = x // a + x // b + x // c cnt -= x // lcm(a, b) + x // lcm(a, c) + x // lcm(b, c) cnt += x // lcm(a, b, c) return cnt >= n
left = 0 right = min(a, b, c) * n while left <= right: mid = (left + right) // 2 if check(mid): right = mid - 1 else: left = mid + 1 return left
classSolution: defnthUglyNumber(self, k: int, a: int, b: int, c: int) -> int: defcheck(m: int) -> bool: # 計算比 m 小的組合數量有幾個,返回 m 是否在第 n 小的組合以後 cnt = 0 for i inrange(1, 1 << 3): cur = 1# lcm for j, x inenumerate([a, b, c]): if i >> j & 1: cur = math.lcm(cur, x) cnt += m // cur if i.bit_count() & 1else -(m // cur) return cnt >= k # return bisect_left(range(min([a, b, c]) * k), True, k, key=check) left, right = k - 1, min([a, b, c]) * k # [left, right] while left <= right: mid = (left + right) // 2 if check(mid): right = mid - 1 else: left = mid + 1 return left