Python 醜數

把只包含因子2,3和5的數稱作醜數(Ugly Number)。
例如6,8都是醜數,但14不是,因爲它包含質因子7。習慣上我們把1當做是第一個醜數。求按從小到大的順序的第N個醜數。

方法一,運行速率慢,當N較大時尤爲明顯:

# -*-coding:utf-8 -*-
class Solution:
    def GetUglyNumber_Solution(self, index):
        if index < 1:
            return None

        count = 0

        def isUglyNumber(num):
            while num % 2 == 0:
                num = num / 2
            while num % 3 == 0:
                num = num / 3
            while num % 5 == 0:
                num = num / 5
            if num == 1:
                return True
            else:
                return False


        num = 1

        while True:
            if isUglyNumber(num):
                count += 1
            if count == index:
                return num
            num += 1


if __name__ == '__main__':
    s = Solution()
    ret = s.GetUglyNumber_Solution(10)
    print(ret)

運行結果爲:

12

方法二,運行速度快,應該採用該方法:

# -*-coding:utf-8 -*-
class Solution:
    def GetUglyNumber_Solution(self, index):
        if index < 1:
            return 0

        uglyList = [1]
        twoPointer = 0
        threePointer = 0
        fivePointer = 0
        count = 1
        while count != index:
            minValue = min(2 * uglyList[twoPointer], 3 * uglyList[threePointer], 5 * uglyList[fivePointer])
            uglyList.append(minValue)
            count += 1
            if minValue == 2 * uglyList[twoPointer]:
                twoPointer += 1

            if minValue == 3 * uglyList[threePointer]:
                threePointer += 1

            if minValue == 5 * uglyList[fivePointer]:
                fivePointer += 1
        return uglyList[count - 1]


if __name__ == '__main__':
    s = Solution()
    ret = s.GetUglyNumber_Solution(200)
    print(ret)

運行結果爲:

16200
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章