1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public int nthUglyNumber(int n, int a, int b, int c) { long ab = lcm(a, b), ac = lcm(a, c), bc = lcm(b, c), abc = lcm(a, lcm(b, c)); long left = 0, right = (long) Math.min(a, Math.min(b, c)) * n; while (left < right) { long mid = left + right >> 1; if (mid / a + mid / b + mid / c - mid / ab - mid / ac - mid / bc + mid / abc >= n) right = mid; else left = mid + 1; } return (int) right; }
private long lcm(long a, long b) { return a * b / gcd(a, b); }
private long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } }
|