Description
Ugly numbers is numbers whose only prime factors is 2, 3 or 5. The sequence
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...
Shows the first one ugly numbers. By convention, 1 is included.
Write a program to find and print the "th ugly number."
Input and Output
There is no. input to the program. Output should consist of a single line as shown below, with <number> replaced by the number computed.
Sample Output
The "th ugly number is <number>.
Idea: Use an array of length 1500 to store these numbers, and another three cursors x, Y, Z;
A[1]=1,x=y=z=1, representing the first number as 1, after which the number is obtained by multiplying the number of 2,3,5,
Then x, Y, z represent a[x],a[y],a[z] can be multiplied by 2,3,5 to get a new number, I increment, each fetch 2*a[x], 3*a[y], 5*a[z]
A[i], the corresponding x (or y,z) can be shifted to the right, of course, if the original 3*2 obtained 6, then 2*3 can also get 6,
Therefore, it is possible that both X and y need to increment.
#include <iostream>
using namespace std;
int min (int a, int b, int c)
{
return min (a,min (b,c));
}
int main ()
{
int a[1517];
int x, y, z, i;
x = y = z = 1, a[1] = 1;
for (i = 2; I <=; i++)
{
A[i] = min (2*a[x],3*a[y],5*a[z]);
if (a[i] = = 2*a[x])
x + +;
if (a[i] = = 3*a[y])
y++;
if (a[i] = = 5*a[z])
z++;
}
int n;
while (CIN >> n && N)
{
cout<<a[n]<<endl;
}
return 0;
}