First, we can enumerate different numbers as a candidate answer as long as there are n - 1's ugly numbers before it.
So, right now we have three conditions here, the first one is all the ugly numbers should be smaller than the answer. The second condition is all the ugly numbers should be divisible by a, b, c. The third condition is there are total of n - 1's ugly numbers before answer.
THe first condition is easy to solve.
The second condition is easy to solve too.
The only annoying condition is the last condition. How to count how many ugly number are smaller than the current number?
for example, we have 3 6 9 12
let say a is 3.
how many ugly number that is divisible by 3 and smaller than 12? the answer is 12/ 3.
as 6 9 12 are all the multiple of 3, we can ensure how many times 3 is able to multiply itself.
But there are a, b, c, there will occur some duplicate cases.
ans/a + ans/b + ans/c - ans/lcm(a,b) - ans/lcm(a,c) - ans/lcm(b, c) + ans/lcm(a,b,c)
typedef long long ll;
class Solution {
public:
ll gcd(ll a, ll b){
if(!b)return a;
return gcd(b, a % b);
}
ll lcm(ll a, ll b){
return a * b / gcd(a, b);
}
ll lcm2(ll a, ll b, ll z){
int res = lcm(a, b);
return lcm(res, z);
}
ll nthUglyNumber(int n, int a, int b, int c) {
ll l = 0, r = INT_MAX;
while(l <= r){
ll mid = (l + r) / 2;
ll cnt = mid/a + mid/b + mid/c - mid/(lcm(a,b)) - mid/(lcm(a,c)) - mid/(lcm(b,c)) + mid/lcm2(a,b,c);
if(cnt < n){
l = mid + 1;
}else{
r = mid - 1;
}
}
return l;
}
};
264. Ugly Number ll
Every time, we generate a new number by multiplying a number by 2/ 3/ 5, we will always make sure the number is minimum, and if we used a 2/3/5, we have to increase the pointer by 1, it will naturally create a sorted array which all the number only have 2/3/5 factors.
class Solution {
public:
int nthUglyNumber(int n) {
vector<int> v(n + 1, 1);
int t1 = 0, t2 = 0, t3 = 0;
for(int i = 1; i <= n; i++){
v[i] = min(v[t1]*2, min(v[t2]*3, v[t3]*5));
if(v[i] == v[t1]*2) t1++;
if(v[i] == v[t2]*3) t2++;
if(v[i] == v[t3]*5) t3++;
}
return v[n - 1];
}
};