Skip to content

Commit a38bed2

Browse files
authored
Create ugly_numbers.py
1 parent fc99aa2 commit a38bed2

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# Python program to find n'th Ugly number
2+
# Method : Dynamic Programming
3+
# Abhishek Sharma. 2021
4+
5+
# Problem Statement : Ugly numbers are numbers whose
6+
# only prime factors are 2, 3 or 5.
7+
# Find out the nth Ugly number, where n is
8+
# given as the input to the program.
9+
10+
# -----------------------------------------------------------------
11+
12+
# Function to get the nth ugly number
13+
14+
def getNthUglyNo(n):
15+
16+
ugly = [0] * n # To store ugly numbers
17+
18+
# 1 is the first ugly number
19+
ugly[0] = 1
20+
21+
# i2, i3, i5 will indicate indices for
22+
# 2,3,5 respectively
23+
i2 = i3 = i5 = 0
24+
25+
# Set initial multiple value
26+
next_multiple_of_2 = 2
27+
next_multiple_of_3 = 3
28+
next_multiple_of_5 = 5
29+
30+
# Start loop to find value from
31+
# ugly[1] to ugly[n]
32+
for l in range(1, n):
33+
34+
# Shoose the min value of all
35+
# available multiples
36+
ugly[l] = min(next_multiple_of_2,
37+
next_multiple_of_3,
38+
next_multiple_of_5)
39+
40+
# Increment the value of index accordingly
41+
if ugly[l] == next_multiple_of_2:
42+
i2 += 1
43+
next_multiple_of_2 = ugly[i2] * 2
44+
45+
if ugly[l] == next_multiple_of_3:
46+
i3 += 1
47+
next_multiple_of_3 = ugly[i3] * 3
48+
49+
if ugly[l] == next_multiple_of_5:
50+
i5 += 1
51+
next_multiple_of_5 = ugly[i5] * 5
52+
53+
# Return ugly[n] value
54+
return ugly[-1]
55+
56+
# Driver Code
57+
if __name__ == '__main__':
58+
print ("- Finding out n'th Ugly Number using Dynamic Method -")
59+
print ("-----------------------------------------------------")
60+
n = int(input("Enter any number : "))
61+
print ()
62+
print ("********************************************")
63+
print ("The desired Ugly number is : ",getNthUglyNo(n))
64+
65+
66+
67+
# -----------------------------------------------------------------
68+
# Input given :
69+
# - Finding out n'th Ugly Number using Dynamic Method -
70+
# -----------------------------------------------------
71+
# Enter any number : 150
72+
73+
# -----------------------------------------------------
74+
# Output :
75+
# The desired Ugly number is : 5832
76+
77+
# -----------------------------------------------------------------
78+
79+
# Code contributed by, Abhishek Sharma, 2021

0 commit comments

Comments
 (0)