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