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.
class Solution {
public:
int nthUglyNumber(int n) {
if(n<=0)
return -1;
int array[n];
array[0]=1;
int *p2=array;
int *p3=array;
int *p5=array;
int nextindex=1;
while(nextindex<n){
array[nextindex]=min(min(*p2*2,*p3*3),*p5*5);
while(*p2*2<=array[nextindex])
++p2;
while(*p3*3<=array[nextindex])
++p3;
while(*p5*5<=array[nextindex])
++p5;
++nextindex;
}
return array[n-1];
}
};