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


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值