題目
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的不是丑數(shù)
- 大于1的時候觉吭,如果能被2整除年局,就循環(huán)除以2歼争,直到不能被2整除应闯;同理對3,5執(zhí)行同樣操作
- 等于1的話是丑數(shù)巧勤,不等于1(大于1)說明該數(shù)還有其他因子秦士,不是丑數(shù)
代碼
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
}