Skip to content

Commit d238432

Browse files
authored
Create ugly-number-iii.py
1 parent 275a43c commit d238432

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Python/ugly-number-iii.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Time: O(logn)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def nthUglyNumber(self, n, a, b, c):
6+
"""
7+
:type n: int
8+
:type a: int
9+
:type b: int
10+
:type c: int
11+
:rtype: int
12+
"""
13+
def gcd(a, b):
14+
while b:
15+
a, b = b, a % b
16+
return a
17+
18+
def lcm(x, y):
19+
return x//gcd(x, y)*y
20+
21+
def count(x, a, b, c, lcm_a_b, lcm_b_c, lcm_c_a, lcm_a_b_c):
22+
return x//a + x//b + x//c - (x//lcm_a_b + x//lcm_b_c + x//lcm_c_a) + x//lcm_a_b_c
23+
24+
lcm_a_b, lcm_b_c, lcm_c_a = lcm(a, b), lcm(b, c), lcm(c, a)
25+
lcm_a_b_c = lcm(lcm_a_b, lcm_b_c)
26+
27+
left, right = 1, 2*10**9
28+
while left <= right:
29+
mid = left + (right-left)//2
30+
if count(mid, a, b, c, lcm_a_b, lcm_b_c, lcm_c_a, lcm_a_b_c) >= n:
31+
right = mid-1
32+
else:
33+
left = mid+1
34+
return left

0 commit comments

Comments
 (0)