POJ 1338 Ugly Numbers,poj1338
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
分析:
這個題的關鍵是類比出來規律,然後用篩法離線求出1500個醜數。
一開始用了一種比較慢的演算法類比了一下
代碼如下
//第一時間想到的低效演算法#include <iostream>#include <cstring>#include <string>using namespace std;int ans[1505];const int tt[3]={2,3,5};bool ugly(int x){while(x!=1){if(0==x%2)x/=2;else if(0==x%3)x/=3;else if(0==x%5)x/=5;elsereturn false;}return true;}int main(){int n,i,k;k=0;ans[k]=1;for(i=2;k<1500;i++){if(ugly(i))ans[++k]=i;}while(cin>>n, n>0){cout<<ans[n-1]<<endl;}return 0;}
之後用篩法類比出1500個醜數AC的
#include <iostream>#include <cstring>#include <string>#include <algorithm>using namespace std;int ans[1505];int main(){int n,i,j,k,t;memset(ans,0,sizeof(ans));ans[1]=1;i=1,j=1,k=1;for(t=2; t<=1500; t++){ans[t]=min(min(ans[i]*2,ans[j]*3),ans[k]*5);if(ans[i]*2==ans[t])++i;if(ans[j]*3==ans[t])++j;if(ans[k]*5==ans[t])++k;}while(cin>>n, n>0)cout<<ans[n]<<endl;return 0;}