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) {
vector<int> res(1, 1);
int p2 = 0, p3 = 0, p5 = 0;
while(res.size() < n){
int tmp2 = res[p2] * 2;
int tmp3 = res[p3] * 3;
int tmp5 = res[p5] * 5;
int tmp = min(tmp2, min(tmp3, tmp5));
if (tmp == tmp2) p2++;
if (tmp == tmp3) p3++;
if (tmp == tmp5) p5++;
res.push_back(tmp);
}
return res.back();
}
};