丑数是指不能被2,3,5以外的其他素数整除的数。丑数从小到大排列起来,结果如下:
1,2,3,4,5,6,8,9,12,15...
求第1500个丑数。
分析:
* 对任意一个丑数x 2x,3x,5x都是丑数(丑数一定由2,3,5的乘积构成,1除外)
* 但一个丑数可能有不同的生成顺序,需要判断这个丑数是否已经存在。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <queue>
#include <set>
using namespace std;
typedef long long LL;
const int coeff[3] = { 2,3,5 };
int main()
{
priority_queue< LL, vector<LL>, greater<LL> > pq;
set<LL> s; //判断是否重复生成
pq.push(1);
s.insert(1);
for (int i = 1;; i++) {
LL x = pq.top(); pq.pop();//取出最小的元素生成三个新元素或输出
if (i == 1500) { //前面已经pop了1499个比x小的元素,x就是第1500个丑数
cout << "The 1500'th ugly number is " << x << "." << endl;
break;
}
for (int j = 0; j < 3; j++) {
LL y = x * coeff[j];
if (!s.count(y)) {
s.insert(y);
pq.push(y);
}
}
}
return 0;
}