The sword refers to the offer: ugly numbers (Python)

Topic description

A number containing only the factors 2, 3 and 5 is called an Ugly Number. For example, 6 and 8 are ugly numbers, but 14 is not because it contains the factor 7. Traditionally we treat 1 as the first ugly number. Find the Nth ugly number in ascending order.

Problem solving ideas

If p is an ugly number, then p=2^x * 3^y * 5^z. Then as long as you assign x, y, zdifferent values ​​can get different ugly numbers.

Python code

def GetUglyNumber_Solution(self, index):
    if index < 1:
        return 0
    res = [1]
    t2,t3,t5 = 0,0,0
    while len(res) < index:
        minNum = (min(res[t2]*2, res[t3]*3, res[t5]*5))
        if minNum > res[-1]: res.append(minNum)
        if (res[-1] == res[t2]*2): t2 += 1
        elif (res[-1] == res[t3]*3): t3 += 1
        else: t5 += 1
    return res[-1]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324855877&siteId=291194637