263. Ugly Number——只由特定质因子组成的数
Difficulty: Easy
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.
bool isUgly(int num) {
int p[3]={2,3,5}; //质因子数组
int i;
if(num<=0)
return false;
if(num==1) //规定1是ugly number
return true;
for(i=0;i<3;i++)
{
while(num%p[i]==0)
{
num=num/p[i]; //若p[i]是num的质因子,一直除 p[i]直到num不再含有质因子p[i]
}
if(num==1)
return true;
}
return false;
}
还能更快吗?不知。。