poj1338 ugly number 题解 打表
类似的题目有HDU1058 humble number(翻译下来都是丑陋的数字)。
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
题目大意:求出第n个丑数,丑数的定义为该整数的质因数仅有2或3或5或没有质因数(因此1在这道题目也是丑数),当然也可以理解成2,3,5互乘所得到的数字就是丑数,例如15是丑数因为他的质因数仅仅为3,5,28不是丑数,因为他的质因数里面有7
思路:这道题目理解完题意之后最让人头疼的是如何打出一个升序顺序的表,而且这个表要保证这些数要符合题意又不能有所缺漏。我们可以利用定义num2,num3,num5来标记乘过2、3、5的最大数字的下标,当biao[i] == biao[numx] * x的时候(x表示2或3或5),我们让numx ++,而且我们要注意在用if语句判断时不要使用else if 来判断,否则这个表会有几个数字是相同的(例如2*3==6,3*2==6,不过是用else if的话肯定会有两个6)。
代码:
//POJ1338
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#define MAXN 1510
using namespace std;
int biao[MAXN + 5];
void makeprime()
{
biao[1] = 1;
int num2 = 1, num3 = 1, num5 = 1;
for(int i = 2;i <= 1510; i ++)
{
biao[i] = min(biao[num2] * 2, min(biao[num3] * 3, biao[num5] * 5));
if(biao[i] == biao[num2] * 2) num2 ++;
if(biao[i] == biao[num3] * 3) num3 ++;
if(biao[i] == biao[num5] * 5) num5 ++;
}
}
int main()
{
makeprime();
int n;
while(scanf("%d", &n) != EOF, n)
{
printf("%d\n", biao[n]);
}
return 0;
}
本文来自博客园,作者:MrYu4,转载请注明原文链接:https://www.cnblogs.com/MrYU4/p/15778911.html