263_Ugly Number

Write a program to check whether a given number is an ugly number.spa

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.code

Note that 1 is typically treated as an ugly number.blog

 

ugly number指的是因子最终能分解成2 3 5的数字,1也认为是特殊的ugly numberit

循环相除,能被2 3 5之一整除的话,继续循环,知道一个数字不能被2 3 5任何数字整除。此时这个数字不是1的话,则说明这个num不是ugly number,如果1的话则说明是ugly number。class

 

bool isUgly(int num) {
    if(num < 1)
    {
        return 0;
    }
    while(num > 1)
    {
        if(num % 2 == 0)
        {
            num /= 2;
            continue;
        }
        else if(num % 3 == 0)
        {
            num /= 3;
            continue;
        }
        else if(num % 5 == 0)
        {
            num /= 5;
            continue;
        }
        return 0;
    }
    return 1;
}
相关文章
相关标签/搜索