请你帮忙设计一个程序,用来找出第 n 个丑数。
丑数是可以被 a 或 b 或 c 整除的 正整数。
示例 1:
输入:n = 3, a = 2, b = 3, c = 5
输出:4
解释:丑数序列为 2, 3, 4, 5, 6, 8, 9, 10… 其中第 3 个是 4。
示例 2:
输入:n = 4, a = 2, b = 3, c = 4
输出:6
解释:丑数序列为 2, 3, 4, 6, 8, 9, 10, 12… 其中第 4 个是 6。
示例 3:
输入:n = 5, a = 2, b = 11, c = 13
输出:10
解释:丑数序列为 2, 4, 6, 8, 10, 11, 12, 13… 其中第 5 个是 10。
示例 4:
输入:n = 1000000000, a = 2, b = 217983653, c = 336916467
输出:1999999984
提示:
1 <= n, a, b, c <= 10^9
1 <= a * b * c <= 10^18
本题结果在 [1, 2 * 10^9] 的范围内
Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search.
Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result.
k/a+k/b+k/c-k/lcm(a,b)-k/lcm(a,c)-k/lcm(b,c)+k/lcm(a,lcm(b,c))
class Solution {
public:
typedef long long LL;
LL lcm(LL a, LL b){
//求a、b的最小公倍数,注意这里a,b要写成LL型
LL sum=a*b;
while(b){
LL tmp=a;
a=b;
b=tmp%b;
}
return sum/a;
}
LL countUglyNumber(int k,int a,int b,int c){
//即f(k):计算k是第几个丑数
return k/a+k/b+k/c-k/lcm(a,b)-k/lcm(a,c)-k/lcm(b,c)+k/lcm(a,lcm(b,c));
}
int nthUglyNumber(int n, int a, int b, int c) {
//二分查找第n个丑数
LL left=min(a,min(b,c));//
LL right=n*left;
while(left<right){
LL mid=left+((right-left)>>1);
int num=countUglyNumber(mid,a,b,c);//计算mid是第几个丑数
if(num<n){
left=mid+1;
}else {
right=mid;
}
}
return left;//此时left为最左边界
}
};