-
Notifications
You must be signed in to change notification settings - Fork 0
/
ugly_no.py
50 lines (32 loc) · 1.17 KB
/
ugly_no.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
#https://www.geeksforgeeks.org/ugly-numbers/
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):
# choose 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]
def main():
n = 11
print ("un is",getNthUglyNo(n) )
if __name__ == '__main__':
main()