We can count how many numbers ≤ x are divisible by a, b, or c using inclusion-exclusion. Use binary search to find the smallest x such that the count is at least n.
classSolution {
publicintnthUglyNumber(int n, int a, int b, int c) {
long l = 1, r = 2000000000L;
long ab = lcm(a, b), ac = lcm(a, c), bc = lcm(b, c), abc = lcm(a, lcm(b, c));
while (l < r) {
long m = l + (r - l) / 2;
long cnt = m/a + m/b + m/c - m/ab - m/ac - m/bc + m/abc;
if (cnt < n) l = m + 1;
else r = m;
}
return (int)l;
}
longlcm(long x, long y) { return x * y / gcd(x, y); }
longgcd(long x, long y) { return y == 0 ? x : gcd(y, x % y); }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
defnthUglyNumber(n, a, b, c):
from math import gcd
deflcm(x, y): return x * y // gcd(x, y)
ab, ac, bc = lcm(a, b), lcm(a, c), lcm(b, c)
abc = lcm(a, bc)
l, r =1, 2*10**9while l < r:
m = (l + r) //2 cnt = m//a + m//b + m//c - m//ab - m//ac - m//bc + m//abc
if cnt < n:
l = m +1else:
r = m
return l