我们把只包含因子2、3和5的数称作丑数(Ugly Number)。例如6、8都是丑数,但14不是,因为它包含因子7。习惯上我们把1当做是第一个丑数。求按从小到大的顺序的第1500个丑数。
注:1是第一个丑数。
简单的做法是,从1开始遍历所有的数,从中累计丑数个数。
那么怎么知道为丑数呢?先判断只能被2,3,5 整除代码如下:
bool is_ugly(int number)
{
while (number % 2 == 0)
{
number = number / 2;
}
while (number % 3 == 0)
{
number = number / 3;
}
while (number % 5 == 0)
{
number = number / 5;
}
return number == 1;
}
另一种方法是,不用这样计算,而是利用空间换时间的方式,利用以计算的丑数,在分别乘以2,3,5.
有朋友会问,那么怎么统计呢?这是关键。
2,3,5去乘以之前计算出来的丑数是有技巧的。
首先,第一个丑数是1,再者是2,3,4,5,6,8,9,10,12
如果需按顺序找第k个,那么首先的找目前的下一个丑数,
从4开始下一个 2*3,3*2,5*2,最小的为6,但俩个都是,则俩者都得移动,
再下一个2*4,3*3,5*2,为8,2的下标的向前移动移位。
具体看代码:
#include <iostream>
#include <algorithm>
#include <cassert>
#include "vld.h"
using namespace std;
int find_ugly(int k);
int main()
{
int k;
cin>>k;
cout<<find_ugly(k)<<endl;
return 0;
}
int find_ugly(int k)//1作为第一个丑数
{
assert(k >= 0);
int *array = new int[k];//从0开始
array[0] = 1;
int index_2 = 0;
int index_3 = 0;
int index_5 = 0;
int count = 1;
while(count < k )
{
int min_val = min(array[index_2]*2,min(array[index_3]*3,array[index_5]*5));//寻找最小的
if (array[index_2]*2 == min_val) //等于最小值就前进一个 如2*3的情形
{
index_2++;
}
if (array[index_3]*3 == min_val)
{
index_3++;
}
if (array[index_5]*5 == min_val)
{
index_5++;
}
array[count] = min_val;
count ++;
}
int res = array[k-1];
delete array;
return res;
}