poj1338 ugly number 題解 打表

來源:互聯網
上載者:User

類似的題目有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

1290

Sample Output

1210

題目大意:求出第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 1510using 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;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.