1. 程式人生 > >POJ 1338題解

POJ 1338題解

描述
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.
輸入
Each line of the input contains a postisive integer n (n <= 1500).Input is terminated by a line with n=0.
輸出
For each line, output the n’th ugly number .:Don’t deal with the line with n=0.
樣例輸入
1
2
9
0
樣例輸出
1
2
10
來源
New Zealand 1990 Division I,UVA 136

題目要求我們輸入一個數字n,輸出第n個醜數,醜數的要求是為其質數因子僅有2、3、5。
一開始的思路是用三重for語句進行列舉,把符合的數字放入答案ans陣列之中去,但是顯然這個方法花費太大了,後來我看到有一個思路非常巧妙,可以根據其大小順序生成答案陣列。程式碼如下:

#include<iostream>
#include<cmath>
using namespace std;
const int num=1510;
int ans[num];
void getans(){
	ans[1]=1;
	int amount_2=1;
	int amount_3=1;
	int
amount_5=1; for(int i=2;i<num;i++){ ans[i]=min(ans[amount_2]*2,min(ans[amount_3]*3,ans[amount_5]*5)); if(ans[i]==ans[amount_2]*2) //2參與了貢獻,遞增之 amount_2++; if(ans[i]==ans[amount_3]*3) amount_3++; if(ans[i]==ans[amount_5]*5) amount_5++; } } int main(){ int n; getans()
; while(cin>>n){ if(n==0) return 0; //輸入結束,程式終止 cout<<ans[n]<<endl; } return 0; }

這裡通過對三個質因數的個數遞加來向前,並且確保每次都是當前最小的數值填入到ans這個陣列中,例如6就是由於2和3的貢獻,這樣把2與3的數量都++,可以避免重複!