// 面试题49:丑数
// 题目:我们把只包含因子2、3和5的数称作丑数(Ugly Number)。求按从小到
// 大的顺序的第1500个丑数。例如6、8都是丑数,但14不是,因为它包含因子7。
// 习惯上我们把1当做第一个丑数。
// ====================算法1的代码====================
static uint32_t get_ugly_num(uint32_t index)
{
if(index < 1)
{
return 0;
}
uint32_t number = 0;
uint32_t count = 0;
while(count < index)
{
++number;
if(_is_ugly(number))
{
++count;
}
}
return number;
}
static bool _is_ugly(uint32_t number)
{
while(number % 2 == 0)
{
number /= 2;
}
while(number % 3 == 0)
{
number /= 3;
}
while(number % 5 == 0)
{
number /= 5;
}
return (number == 1) ? true : false;
}
// ====================算法2的代码====================
static uint32_t get_ugly_num2(uint32_t index)
{
if(index < 1)
{
return 0;
}
std::vector<uint32_t> arr(index, 1);
uint32_t next_index = 1;
uint32_t ind2 = 0;
uint32_t ind3 = 0;
uint32_t ind5 = 0;
auto min_num = [](uint32_t n1, uint32_t n2, uint32_t n3)
{
auto mi = std::min(n1, n2);
return std::min(mi, n3);
};
while(next_index < index)
{
auto min = min_num(arr[ind2] * 2, arr[ind3] * 3, arr[ind5] * 5);
arr[next_index] = min;
while(arr[ind2] * 2 <= min)
{
++ind2;
}
while(arr[ind3] * 3 <= min)
{
++ind3;
}
while(arr[ind5]* 5 <= min)
{
++ind5;
}
++next_index;
}
return arr[next_index - 1];
}