問題描述
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.
補充說明:
輸入一個數字,判斷這個數字是不是丑陋數。何為丑陋數,所謂的丑陋數就是如果一個數它的全部質因數在集合2、 3、 5這三個數字組成的集合中,則這個數字是丑陋數。
方案分析
- 要搞定這個問題,首先需要了解一個概念,叫做質因數。這里有個鏈接講的特別生動,筆者就不贅述了。prime factor。
- 看懂上面那個鏈接的內容,想必大家都有了思路了吧。這個問題其實比求質因數還簡單。因為這個已經限定了質因數的集合了。上代碼,自己揣摩。
python實現
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num == 0:
return False
check_list = [2, 3, 5]
for i in check_list:
while(num % i == 0):
num /= i
if num == 1:
return True
return False
方案分析2
- 在OJ上看到了另外一個解決方案,這個更加粗暴。你不是說質因素只能包含這3個數字的子集嗎?好,就反復除以這3個數字,直到再無法進行下去。然后判斷最后的結果數字是否為1。為1則表明只包含這3個數字的子集。
python實現2
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num == 0: return False
if num == 1: return True
while(num % 2 == 0):
num /= 2
while(num % 3 == 0):
num /= 3
while(num % 5 == 0):
num /= 5
return num == 1