Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...
shows the first 11 ugly numbers. By convention, 1 is included.
Write a program to find and print the 1500’th ugly number.
Input
There is no input to this program.
Output
Output should consist of a single line as shown below, with ‘’ replaced by the number computed.
Sample Output
The 1500'th ugly number is .
问题链接:UVA136 Ugly Numbers。
题意简述:
不能被2、3和5以外的素数整除的数称为丑数,找出第1500个丑数。
问题分析:
换句话说,丑数的因子只能是2、3和5。1是丑数,对于x,若x是丑数则2x、3x和5x是丑数。利用已知的丑数,从小到不断生成丑数就可以了。
程序说明:
使用一个STL的容器set来存放丑数。集合具有去重复,自动排序的功能,十分方便。
AC的C++语言程序如下:
/* UVA136 Ugly Numbers */
#include <iostream>
#include <cstdio>
#include <set>
using namespace std;
#define MAXN 1500
typedef unsigned long long ULL;
set<ULL> ugly;
int main(void)
{
int count;
ugly.insert(1);
count = 0;
set<ULL>::iterator iter = ugly.begin();
while(++count < MAXN) {
ULL t = *iter;
ugly.insert(t * 2);
ugly.insert(t * 3);
ugly.insert(t * 5);
iter++;
}
printf("The 1500'th ugly number is %llu.\n", *iter);
return 0;
}