Ugly Numbers
Ugly numbers are numbers whose only prime factors 2, 3 or 5. The sequence
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...
Shows the ugly numbers. By convention, 1 is included.
Write a program to find and print the 150′th ugly number.
Method 1 (Simple)
Nedylko Draganov for suggesting this solution.
Algorithm:
loop for all positive integers until ugly # count is smaller than n, if a integer is ugly than increment ugly Count.
To check if a are ugly, divide the number by greatest divisible powers of 2, 3 and 5, if the number becomes 1 then I T is a ugly number otherwise not.
For example, let us??? Check for/is ugly or not. Greatest divisible power of 2 are 4 after dividing to 4 we get 75. Greatest divisible power of 3 are 3 after dividing to 3 we get 25. Greatest divisible power of 5 was, after dividing and we get 1. Since we get 1 Finally, the ugly is number.
Back to the column page: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
Here's a simple method with a program that can print all ugly number less than N:
int maxdivide (int num, int div)
{while
(num% div = = 0)
{
num/= div;
}
return num;
}
BOOL isugly (int num)
{
num = maxdivide (num, 2);
num = Maxdivide (num, 3);
num = maxdivide (num, 5);
return num = 1? True:false;
}
int Getnthuglyno (int n)
{
int c = 0;
int i = 0;
while (c < n)
{
if (isugly (++i)) C + +;
}
return i;
}
#include <vector>
using Std::vector;
vector<int> Getalluglyno (int n)
{
vector<int> rs;
for (int i = 1; I <= n; i++)
{
if (isugly (i)) rs.push_back (i);
}
return RS;
}