Created
January 15, 2014 02:44
-
-
Save ishahid/8429884 to your computer and use it in GitHub Desktop.
O(N) solution to find Nth ugly number.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def ugly_number(n): | |
""" Returns Nth ugly number """ | |
assert n > 0, 'The argument must be greater than zero.' | |
list = [0]*n | |
i2, i3, i5 = 0, 0, 0 | |
w2, w3, w5 = 2, 3, 5 | |
w, list[0] = 1, 1 | |
for i in range(1, n): | |
w = min(w2, w3, w5) | |
list[i] = w | |
if w == w2: | |
i2 = i2+1 | |
w2 = list[i2]*2 | |
if w == w3: | |
i3 = i3+1 | |
w3 = list[i3]*3 | |
if w == w5: | |
i5 = i5+1 | |
w5 = list[i5]*5 | |
return w | |
if __name__ == "__main__": | |
print 'ugly numbers' | |
print 'first 20:', | |
for n in range(1, 21, 1): | |
print ugly_number(n), | |
print '' | |
print '10th:', | |
print ugly_number(10) | |
print '100th:', | |
print ugly_number(100) | |
print '300th:', | |
print ugly_number(300) | |
print '600th:', | |
print ugly_number(600) | |
print '1200th:', | |
print ugly_number(1200) | |
print '2400th:', | |
print ugly_number(2400) | |
print '4800th:', | |
print ugly_number(4800) | |
print '9600th:', | |
print ugly_number(9600) | |
print '50000th:', | |
print ugly_number(50000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment