Ugly Numbers
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 21453 | Accepted: 9586 |
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
Source
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<cmath> #include<cstdlib> #include<algorithm> #include<queue> #include<vector> #include<stack> using namespace std; int n,ans[1505]; int main() { ans[1]=1; int p1=1,p2=1,p3=1; for(int i=2;i<=1500;i++) { ans[i]=min(ans[p1]*2,min(ans[p2]*3,ans[p3]*5)); if(ans[i]==ans[p1]*2) p1++; if(ans[i]==ans[p2]*3) p2++; if(ans[i]==ans[p3]*5) p3++; } while(scanf("%d",&n)!=EOF) { if(n==0) break; printf("%d\n",ans[n]); } return 0; }
时间: 2024-11-07 00:08:42