问题描述:
Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10
ugly numbers.
Note that 1
is typically treated as an ugly number.
AC代码如下:
int minThree(int x,int y,int z)
{
int temp = x < y ? x : y;
return temp < z ? temp : z;
}
int nthUglyNumber(int n)
{
int count = 0;
int *ugly = new int[n];
memset(ugly,0,sizeof(int)*n);
int index1,index2,index3;
index1 = index2 = index3 = 0;
ugly[0] = 1;
while(count < n-1)
{
int No = minThree(2*ugly[index1],3*ugly[index2],5*ugly[index3]);
if(No == 2*ugly[index1])
{
index1++;
}
if(No == 3*ugly[index2])
{
index2++;
}
if(No == 5*ugly[index3])
{
index3++;
}
count++;
ugly[count] = No;
}
return ugly[count];
}