您的位置:首页 > 其它

寻找丑数

2012-09-21 12:27 453 查看
问题描述:

我们把只包含因子2、3和5的数成为丑数(Ugly Number)。例如6、8都是丑数,但是14不是。我们习惯将1作为第一个丑数。

求从小到大顺序的100个丑数。

问题解答:

穷举,暴力的方法总是可以解决问题的,只是需要你的耐心等待;

维持3个下标,表示前面的数据已分别做过*2、*3、*5操作(下标初始化为1),维持一个向后移动的结果下标。这样我们每次找出三个下标的数分别*2、*3、*5,取出最小的数,和当前结果的最大数比较,如果大于,放入结果;否则只是*x的下标移动。下面举例说明:

    index2  index3  index5    res        res[index_x] * x

0、    0    0     0      1          2  3  5

1、    1    0     0      1、 2        4  3  5

2、    1    1     0      1、 2、 3      ……

  依次往下走,即可等到我们要的结果

代码如下:

#include <iostream>
using namespace std;

int minofThree(int* res, int& index2, int& index3, int& index5)
{
int res2 = res[index2] * 2;
int res3 = res[index3] * 3;
int res5 = res[index5] * 5;

int tmp = res2 < res3 ? res2 : res3;
int& index = res2 < res3 ? index2 : index3;

int& indexS = tmp < res5 ? index : index5;
tmp = tmp < res5 ? tmp : res5;
indexS++;
return tmp;
}

int findUglyNum(int N)
{
int* res = new int
;
int index = 0;
res[index] = 1;
index++;

int index2 = 0;
int index3 = 0;
int index5 = 0;

while (index < N)
{
int tmp = minofThree(res, index2, index3, index5);
if (res[index - 1] < tmp)
{
res[index++] = tmp;
}
}

for (int i = 0; i < N; i++)
{
cout << res[i] << "\t";
}
cout << endl;
delete [] res;
return 0;
}

int main()
{
int n = 100;
findUglyNum(n);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: