Skip to content

Commit 275a43c

Browse files
authored
Create ugly-number-iii.cpp
1 parent 0d1a82d commit 275a43c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

C++/ugly-number-iii.cpp

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Time: O(logn)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int nthUglyNumber(int n, int a, int b, int c) {
7+
int64_t lcm_a_b = lcm(a, b), lcm_b_c = lcm(b, c), lcm_c_a = lcm(c, a);
8+
int64_t lcm_a_b_c = lcm(lcm_a_b, lcm_b_c);
9+
int64_t left = 1, right = 2 * 1e9;
10+
while (left <= right) {
11+
const auto& mid = left + (right - left) / 2;
12+
if (count(mid, a, b, c,
13+
lcm_a_b, lcm_b_c, lcm_c_a, lcm_a_b_c) >= n) {
14+
right = mid - 1;
15+
} else {
16+
left = mid + 1;
17+
}
18+
}
19+
return left;
20+
}
21+
22+
private:
23+
int64_t count (int64_t x,
24+
int64_t a, int64_t b, int64_t c,
25+
int64_t lcm_a_b, int64_t lcm_b_c, int64_t lcm_c_a,
26+
int64_t lcm_a_b_c) {
27+
return x / a + x / b + x / c - (x / lcm_a_b + x / lcm_b_c + x / lcm_c_a) + x / lcm_a_b_c;
28+
}
29+
30+
int64_t gcd(int64_t a, int64_t b) {
31+
while (b != 0) {
32+
const auto tmp = b;
33+
b = a % b;
34+
a = tmp;
35+
}
36+
return a;
37+
}
38+
39+
int64_t lcm(int64_t a, int64_t b) {
40+
return a / gcd(a, b) * b;
41+
}
42+
};

0 commit comments

Comments
 (0)