首页 > 试题广场 >

把只包含因子2、3和5的数称作丑数(Ugly Number)

[问答题]
把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
def nth_ugly_number(n): count = 1 num = 1 while count < n: num += 1 temp = num while temp % 2 == 0: temp //= 2 while temp % 3 == 0: temp //= 3 while temp % 5 == 0: temp //= 5 if temp == 1: count += 1 return num
发表于 2024-11-02 17:05:53 回复(0)