JZ33:丑数【Python】

丑数

http://www.nowcoder.com/questionTerminal/6aa9e04fc3794f68acf8778237ba065b

题目描述
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含质因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。

简述:小白的简单思路,时间复杂度较高网站可能通过不了,但是私下跑过程序,结果应该没问题。

class Solution:
def GetUglyNumber_Solution(self, index):
# write code here
indexOfUgly = 1
location = 1
res = 1
if index <= 0:
return None
if index == 1:
return 1

    while indexOfUgly != index:
        location = location + 1
        # print("正在判断{}是否为丑数".format(location))
        if self.is_UglyNumber(location):
            res = location
            indexOfUgly = indexOfUgly + 1
            print("第{}个丑数是{}".format(indexOfUgly, res))
    return res

def is_UglyNumber(self, location):
    condition_one = False
    condition_two = True
    if location % 2 == 0 or location % 3 == 0 or location % 5 == 0:
        condition_one = True

    for i in range(7, location):
        sushu = True    # 判断是否为素数
        for j in range(2, i):
            if i % j == 0:
                sushu = False
                break

        if sushu:
            if location % i == 0:
                condition_two = False

    return condition_one and condition_two
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务