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