把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。 习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第N个丑数。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int Min(int n1, int n2, int n3)
{
int min = n1 < n2 ? n1 : n2;
return min < n3 ? min : n3;
}
int GetUglyNumber_Solution(int index) {
vector<int> array;
array.push_back(1);
int p2, p3, p5;
p2 = p3 = p5 = 0;
int nextPoint = 1;
while (nextPoint<index)
{
int insert = Min(array[p2]*2, array[p3]*3, array[p5]*5);
array.push_back(insert);
while (array[p2] * 2 <= insert)
p2++;
while (array[p3] * 3 <= insert)
p3++;
while (array[p5] * 5 <= insert)
p5++;
nextPoint++;
}
return array[index-1];
}
int main() {
int re = GetUglyNumber_Solution(15);
cout << re << endl;
return 0;
}