Skip to content

Commit 37b1836

Browse files
committed
kth ugly number.
1 parent b29c495 commit 37b1836

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

‎python/dynamic/kth_ugly_number.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
Problem Statement
3+
=================
4+
5+
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15,
6+
shows the first 11 ugly numbers. By convention, 1 is included.
7+
8+
Write a program to find the kth ugly number.
9+
10+
Complexity
11+
----------
12+
13+
* Time Complexity O(n)
14+
* Space Complexity O(n)
15+
16+
Reference
17+
---------
18+
* http://www.geeksforgeeks.org/ugly-numbers/
19+
"""
20+
21+
22+
def ugly_number(kth):
23+
ugly_factors = [1] # By convention 1 is included.
24+
25+
factor_index = {
26+
2: 0,
27+
3: 0,
28+
5: 0}
29+
30+
for num in range(1, kth):
31+
minimal_factor = min(min(ugly_factors[factor_index[2]] * 2, ugly_factors[factor_index[3]] * 3),
32+
ugly_factors[factor_index[5]] * 5)
33+
34+
ugly_factors.append(minimal_factor)
35+
36+
for factor in [2, 3, 5]:
37+
if minimal_factor % factor == 0:
38+
factor_index[factor] += 1
39+
40+
return ugly_factors[kth - 1]
41+
42+
if __name__ == '__main__':
43+
assert 5832 == ugly_number(150)

0 commit comments

Comments
 (0)