@target 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
思路:
这里丑数一定是由2,3,5因子组成,那么逐一尝试对2,3,5取余,若余数为0,则含有某一因子。若均不含有,那一定不是丑数。
public boolean isUgly(int num) {
if(num <= 0){
return false;
}
int num2 = num % 2;
int num3 = num % 3;
int num5 = num % 5;
while(num2 == 0||num3 == 0||num5 == 0){
if(num2 == 0){
num = num / 2;
}
else if(num3 == 0){
num = num / 3;
}
else {
num = num / 5;
}
num2 = num % 2;
num3 = num % 3;
num5 = num % 5;
}
return num == 1;
}