poj1338 Ugly Numbers(醜數類比)

來源:互聯網
上載者:User

標籤:數學   poj   遞推   

轉載請註明出處:http://blog.csdn.net/u012860063?viewmode=contents

題目連結:http://poj.org/problem?id=1338


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

思路:用一個長度為1500的數組儲存這些數,另有三個遊標x,y,z;

a[1]=1,x=y=z=1,代表第一個數為1,此後的數都是通過已有的數乘以2,3,5得到的,
那麼x,y,z分別代表a[x],a[y],a[z]可以通過乘以2,3,5來得到新的數,i遞增,每次取2*a[x], 3*a[y], 5*a[z]
中的最小值,得到a[i]後,可以將對應的x(或y,z)右移,當然如果原本通過3*2得到6,那麼2*3也能得到6,
因此可能x和y都需要遞增。

詳見代碼:

#include <iostream>using namespace std;int min(int a, int b, int c){return min(a,min(b,c));}int main(){int a[1517];int x, y, z, i;x = y = z = 1, a[1] = 1;for(i = 2; i <= 1500; i++){a[i] = min(2*a[x],3*a[y],5*a[z]);if(a[i] == 2*a[x])x++;if(a[i] == 3*a[y])y++;if(a[i] == 5*a[z])z++;}int n;while(cin >> n && n){cout<<a[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.