Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.
思路:如果num可以被2,3,5整除,那么就除以2,3,5.看最后是不是结果等于1.
class Solution: # @param {integer} num # @return {boolean} def isUgly(self, num): if num <= 0: return False for x in [2, 3, 5]: while num % x == 0: num /= x return num == 1
Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10
ugly numbers.
Note that 1
is typically treated as an ugly number.
1 class Solution(object): 2 def nthUglyNumber(self, n): 3 """ 4 :type n: int 5 :rtype: int 6 """ 7 res = [1]*n 8 p2 = 0 9 p3 = 0 10 p5 = 0 11 12 count = 1 13 while count < n: 14 cur = min(res[p2]*2, res[p3]*3, res[p5]*5) 15 if cur == res[p2]*2: 16 p2 += 1 17 elif cur == res[p3]*3: 18 p3 += 1 19 elif cur == res[p5]*5: 20 p5 += 1 21 if cur > res[count-1]: 22 res[count] = cur 23 count += 1 24 return res[-1] 25