一刷 06/2022
Version #1 LCM - Least common multiple
GCD - Greatest Common Divisor
非常好的一道题,再多做几遍[TODO]
class Solution {
public int nthUglyNumber(int n, int a, int b, int c) {
long ab = lcm((long)a, (long)b);
long ac = lcm((long)a, (long)c);
long bc = lcm((long)b, (long)c);
long abc = lcm(a, bc);
// System.out.printf("abc=%d", abc);
long start = 1;
long end = Integer.MAX_VALUE;
while (start < end) {
long mid = start + (end - start) / 2;
long result = mid / a + mid / b + mid / c - mid / ab - mid / ac - mid / bc + mid / abc;
// There are multiple numbers satisfy that there a #result number of unly numbers smaller than or equals to that number
// We want to find the first occurance, so we can't return directly when we found reuslt == n
// if (result == n) {
// return mid;
// }
if (result < n) {
start = mid + 1;
} else {
end = mid;
}
}
return (int)start;
}
private long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
private long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
}
No comments:
Post a Comment