Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 25318 | Accepted: 11094 |
Description
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, ...
shows the first 10 ugly numbers. By convention, 1 is included.
Given the integer n,write a program to find and print the n'th ugly number.
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ...
shows the first 10 ugly numbers. By convention, 1 is included.
Given the integer n,write a program to find and print the n'th ugly number.
Input
Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.
Output
For each line, output the n’th ugly number .:Don’t deal with the line with n=0.
Sample Input
1 2 9 0
Sample Output
1 2 10
Source
New Zealand 1990 Division I,UVA 136
问题链接:POJ1338 Ugly Numbers。
题意简述:
不能被2、3和5以外的素数整除的数称为丑数,找出第1500个丑数。
问题分析:
换句话说,丑数的因子只能是2、3和5。1是丑数,对于x,若x是丑数则2x、3x和5x是丑数。利用已知的丑数,从小到不断生成丑数就可以了。
程序说明:
这个问题有两种解法:
解法一:
程序中,使用一个STL的容器set来存放丑数。集合具有去重复,自动排序的功能,对于解决本问题是方便的。但是,set对象无法用下标访问,所以倒腾到vector对象中再使用。本问题打表是合适的。
解法二:
程序中,结果放在数组ans[]中,也是生产丑数的x;素数放在数组prime[]中,这个问题只有2、3和5;生成的丑数放在数组ugly[]中,然后选出最小的放入结果数组ans[]中,对于被放入数组的则计算下一个丑数(从小到大依次生成,逐个放入结果数组中)。
这个解法中,打表是合适的。
AC的C++语言程序如下(解法二):
/* POJ1338 Ugly Numbers */
#include <stdio.h>
#define MAXN 1500
typedef unsigned long long ULL;
ULL ans[MAXN+1] = {0, 1};
void maketable()
{
int prime[] = {2, 3, 5};
ULL ugly[sizeof(prime)/sizeof(prime[0])];
int p[sizeof(prime)/sizeof(prime[0])];
int count, size, i;
size = sizeof(prime)/sizeof(prime[0]);
count = 1;
for(i=0; i<size; i++) {
p[i] = 1;
ugly[i] = ans[p[i]] * prime[i];
}
while(count < MAXN) {
ULL min = ugly[0];
int j = 0;
/* 找出最小元素 */
for(i=1; i<size; i++) {
if(ugly[i] < min) {
min = ugly[i];
j = i;
}
}
/* 生成的丑数没有重复,加入表中 */
if(ans[count] != min)
ans[++count] = min;
/* 生成下一个最小丑数 */
ugly[j] = ans[++p[j]] * prime[j];
}
}
int main(void)
{
int n;
maketable();
while(scanf("%d", &n) != EOF && n != 0)
printf("%llu\n", ans[n]);
return 0;
}
AC的C++语言程序如下(解法一):
/* POJ1338 Ugly Numbers */
#include <iostream>
#include <cstdio>
#include <set>
#include <vector>
using namespace std;
const int MAXN = 1500;
typedef unsigned long long ULL;
set<ULL> uglyset;
vector<ULL> ugly;
void maketable()
{
int count, i;
uglyset.insert(1);
count = 0;
set<ULL>::iterator iter = uglyset.begin();
while(++count < MAXN) {
ULL t = *iter;
uglyset.insert(t * 2);
uglyset.insert(t * 3);
uglyset.insert(t * 5);
iter++;
}
ugly.push_back(0);
iter = uglyset.begin();
for(i=1; i<=MAXN; i++)
ugly.push_back(*iter++);
}
int main(void)
{
int n;
maketable();
while(scanf("%d", &n) != EOF && n != 0)
printf("%llu\n", ugly[n]);
return 0;
}