算法题/丑数

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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值