题目
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.
解题思路
- 小于1的不是丑数
- 大于1的时候,如果能被2整除,就循环除以2,直到不能被2整除;同理对3,5执行同样操作
- 等于1的话是丑数,不等于1(大于1)说明该数还有其他因子,不是丑数
代码
func isUgly(num int) bool {
if num < 1 {
return false
}
for ; num > 1 && num % 2 == 0 ; {
num /= 2
}
for ; num > 1 && num % 3 == 0 ; {
num /= 3
}
for ; num > 1 && num % 5 == 0 ; {
num /= 5
}
if num == 1 {
return true
}
return false
}