Jan 15, 2009

Ugly Numbers

Ugly Numbers
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ... shows the first 11 ugly numbers. By convention, 1 is included. Write a program to find and print the 1500'th ugly number.
f x is ugly, then so are 2x, 3x and 5x.
So use a min-heap.
Start with 2,3,5 in the heap.
Now do the following in a loop:
x = Heap.PopCurrentMin();
Heap.Insert(2x);
Heap.Insert(3x);
Heap.Insert(5x)
I believe this will work. Not sure what the time complexity will be, but my guess is that this is reasonably efficient.

Or
bool IsUgly (unsigned n)
{
if ( n == 0 ) return false;
while ( !(n%2) ) n /= 2;
while ( !(n%3) ) n /= 3;
while ( !(n%5) ) n /= 5;
return !(n-1);
}
unsigned Ugly1500()
{
unsigned n = 0;
unsigned uglyCount = 0;
while ( uglyCount < 1500 )
{
n++;
if ( IsUgly(n) ) uglyCount++;
}
return n;
}
}

No comments:

Post a Comment