POJ 1338 Ugly Numbers,poj1338

來源:互聯網
上載者:User

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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.