标签:
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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
class Solution { public: bool isUgly(int num) { if (num == 1 || num == 2 || num == 3 || num == 5) return true; vector<int> u = {2,3,5}; for (int i = 0; i < u.size(); i++) { if (num % u[i] == 0) { int p = num / u[i]; if (p == 2 || p == 3 || p == 5 || !isPrime(p) && isUgly(p)) return true; } } return false; } bool isPrime(int num) { for (int i = 2; i*i <= num; i++) { if (num % i == 0) return false; } return true; } };
这题花了一番功夫,主要卡在质因数分解上。我的思路是用2,3,5去整除num,如果结果不是2,3,5而且不是其他任何质数的话,它就是ugly的。但是这个思路有个问题,以28为例子,用2除的得14,因此14不是2,3,5中的一个同时也不是质数,所以被判为了ugly。但事实是14还可以被分解为2 x 7, 而7 是质数,因此7 也是28的一个质因子,因此28不是ugly数,怎么办呢,灵机一抖的我想到如果再保证除2,3,5以后的数是ugly的不就解决了。。。所以我在超长的if 语句后面加上isUgly的递归调用,结果证明这个思路是正确的 Accepted.
标签:
原文地址:http://www.cnblogs.com/agentgamer/p/4864978.html