题意
丑数是指不能被2,3,5以外的其他素数整除的数。把丑数从小到大排列起来,结果如下:
1,2,3,4,5,6,8,9,10,12,15……
求第1500个丑数
输入
没有输入
输出
The 1500’th ugly number is .
分析:除了1之外只能被2,3,5整除的数字,一定是由2,3,5作为因子,之后相乘,例如:
4=2X2;
6=2X3;
8=2X4;
10=2X5;
12=2X2X3;
…
所以我们可以把1作为一个因子,然后每次循环都用最小的数分别乘2,3,5,
并且用set 容器进行去重和排序,代码如下:
#include <iostream>
#include <stdio.h>
#include <set>
#include <algorithm>
using namespace std;
#define MAXN 1500
#define LL long long
int main()
{
set<LL> un;
int count = 0;
un.insert(1);
set<LL>::iterator iter = un.begin();
while (++count < MAXN)//这里注意是++count而不是count++
{
LL t = *iter;
un.insert(t * 2);
un.insert(t * 3);
un.insert(t * 5);
iter++;
}
printf("The 1500'th ugly number is %lld.\n", *iter);
return 0;
}