-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathugly-number.py
51 lines (35 loc) · 1.13 KB
/
ugly-number.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Python program to find n'th Ugly number
# Function to get the nth ugly number
def getNthUglyNo(n):
ugly = [0] * n # To store ugly numbers
# 1 is the first ugly number
ugly[0] = 1
# i2, i3, i5 will indicate indices for
# 2,3,5 respectively
i2 = i3 = i5 = 0
# Set initial multiple value
next_multiple_of_2 = 2
next_multiple_of_3 = 3
next_multiple_of_5 = 5
# Start loop to find value from
# ugly[1] to ugly[n]
for l in range(1, n):
# Shoose the min value of all
# available multiples
ugly[l] = min(next_multiple_of_2,
next_multiple_of_3, next_multiple_of_5)
# Increment the value of index accordingly
if ugly[l] == next_multiple_of_2:
i2 += 1
next_multiple_of_2 = ugly[i2] * 2
if ugly[l] == next_multiple_of_3:
i3 += 1
next_multiple_of_3 = ugly[i3] * 3
if ugly[l] == next_multiple_of_5:
i5 += 1
next_multiple_of_5 = ugly[i5] * 5
# Return ugly[n] value
return ugly[-1]
if __name__ == "__main__":
n = 150
print(getNthUglyNo(n))