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.
一个数的因子只包含(only include)2,3,5就是丑数了
其中1也是丑数
- 2,3,5轮流除,能除尽就除,除不尽记录下那个数,然后继续循环,当发现记录的俩数相同的时候就false了,这个判断似乎又回到了 258. Add Digits 利用set或者hash_set来判断,但这个很特殊,只要比较前一次和这一次的值就行,所以不用也可以
#include <vector>
#include <iostream>
using namespace std;
bool ugly (int n)
{
int m=n; //为下面判断用
vector<int> v{2,3,5};
while(n>1)
{
for(int i=0; i<v.size(); ++i)
{
if(n%v[i] == 0)
{
n=n/v[i];
}
}
if(m==n) //判断在这里
{
return false;
}
m=n; //别漏了
}
return true;
}
int main()
{
int n;
cin>>n;
ugly(n);
return 0;
- 网上流传的方法
看了这种再看看我写,我要挖地洞!!!
#include <iostream>
using namespace std;
bool ugly (int n)
{
while(n%2==0)
n /= 2;
while(n%3==0)
n /= 3;
while(n%5==0)
n /= 5;
return (n==1)?true:false;
}
int main()
{
int n;
cin>>n;
ugly(n);
return 0;
}
- 然后就是列出1500个从大到小排序的丑数了
套用上面的函数就行
然而,大神又想出来其他方法,简单说就是为了避免不必要的操作,先把丑数存到一个数组……
http://blog.csdn.net/houzengjiang/article/details/7940148