python2.7
2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第1500个丑数。
所谓一个数m是另一个数n的因子,是指n能被m整除,也就是n % m == 0。根据丑数的定义,丑数只能被2、3和5整除。也就是说如果一个数如果它能被2整除,我们把它连续除以2;如果能被3整除,就连续除以3;如果能被5整除,就除以连续5。如果最后我们得到的是1,那么这个数就是丑数,否则不是。
#coding:utf-8
#判断是否为丑数
def isugly(n):
if n == 1:
return True
else:
while n % 2 ==0:
n = n/2
while n % 3 ==0:
n = n/3
while n % 5 ==0:
n = n/5
return True if n == 1 else False
#找出第1500个丑数
def getchoushu(n):
counter = 1
target = 0
while counter <= n:
for i in range(1,1000):
if isugly(i):
counter += 1
target = i
print('ugly number:',target)
return target
if __name__ == '__main__':
print('the ugly number is :',getchoushu(1500))
1——> 1*2 1*3 1*5
2——>2*2 2*3 2*5
3——> 3*2 3*3 3*5
4——>4*2 4*3 4*5
5——>5*2 5*3 5*5
6—–>6*2 6*3 6*5
8——>8*2 8*3 8*5
方法二
#coding:utf-8
class Choushu:
def get_choushu(self,index):
if index == None and len(index) <=0:
return 0
ugly_numbers=[1]*index
next_index = 1
index_2 = 0
index_3 = 0
index_5 = 0
while next_index < index:
min_val = min(ugly_numbers[index_2]*2,ugly_numbers[index_3]*3,ugly_numbers[index_5]*5)
ugly_numbers[next_index] = min_val
while ugly_numbers[index_2]*2 <= ugly_numbers[next_index]:
index_2 += 1
while ugly_numbers[index_3]*3 <= ugly_numbers[next_index]:
index_3 += 1
while ugly_numbers[index_5]*5 <= ugly_numbers[next_index]:
index_5 += 1
next_index += 1
return ugly_numbers[-1]
c = Choushu()
print(c.get_choushu(15))