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. 

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;
}


posted @   MrYu4  阅读(37)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示