Ugly numbers are numbers whose values only contain factors 2, 3, and 5, and 14 is not ugly because it contains factor 7.
/*int min(int a,int b){
if(a>b){
return b;
}else{
return a;
}
}*/C++中存在min函数,可以直接使用
int nthUglyNumber(int n) {
int num[n+1];
int p2,p3,p5;
p2=p3=p5=0;
num[0]=1;
for(int i=1;i<n;i++)
{
num[i]=min(min(num[p2]*2,num[p3]*3),min(num[p2]*2,num[p5]*5));
if(num[i]==num[p2]*2)
++p2;
if(num[i]==num[p3]*3)
++p3;
if(num[i]==num[p5]*5)
++p5;
}
return num[n-1];
}
1.
The current ugly number must be 2 times, 3 times, or 5 times the previous ugly number k.
Set an integer array num[] to store ugly numbers. The current ugly number is the minimum of 2*num[p2], 3*num[p3], and 5*num[p5], where p2, p3, and p5 are the first p2, p3, p5 are ugly numbers, and the initial values of p2, p3, and p5 are all 0.
2.
Set the first value of the array num[0]=1, multiply 2, 3, and 5 by 1 to find the second ugly number, and get the minimum value of 2 as the second ugly number, that is, num[1]=2.
2*num[p2]=2*num[0]=2*1=2
3*num[p3]=3*num[0]=3*1=3
5*num[p5]=5*num[0 ]=5*1=
5Because the second ugly number is obtained by multiplying 2 and the previous ugly number, there is no need to calculate 2 and the corresponding previous ugly number num[p2] when looking for the ugly number next time Multiply, because the next ugly number must be greater than num[1] or 2*num[0]. Therefore, when calculating the ugly number next time, multiply by 2 directly from nun[1], that is, p2 is carried by one digit.
3.
Use 2*num[p2], 3*num[p3], 5*num[p5] to judge the third ugly number, p2=1, p3=p5=0.
2*num[p2]=2* num[1]=2*2=4
3*num[p3]=3*num[0]=3*1=3
5*num[p5]=5*num[0]=5*1=5
to get the minimum The value 3 is used as the third ugly number, so there is no need to calculate the multiplication of 3 with the correspondingly multiplied previous ugly number num[0] when looking for the ugly number next time, because the next ugly number must be greater than 3*num[0 ] is num[2]. Therefore, when calculating the ugly number next time, directly multiply num[1] by 3, that is, the following table p3 is carried by one digit.
4. By analogy, find the nth smallest value as the nth ugly number.