什么是丑数?
把只包含质因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但7、14不是,因为它们包含质因子7。 习惯上我们把1当做是第一个丑数。
前20个丑数为:1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, 36
求第n个丑数是多少
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int GetUglyNumber(int index)
{
//第N个丑数
//丑数思想 2 3 5为因子 丑数j = 丑数i*(2或者3或者5得到)
if (index < 7)
return index;
vector<int> ivec(index, 0);
ivec[0] = 1;
int t2 = 0, t3 = 0, t5 = 0;
for (int i = 1; i < index; ++i)
{
ivec[i] = min(min(ivec[t2] * 2, ivec[t3] * 3), ivec[t5] * 5);
if (ivec[i] == ivec[t2] * 2)
t2++;
if (ivec[i] == ivec[t3] * 3)
t3++;
if (ivec[i] == ivec[t5] * 5)
t5++;
}
return ivec[index - 1];
}
int main()
{
cout<<GetUglyNumber(10)<<endl;
return 0;
}
运行截图如下