PKU1338:Ugly Numbers

Ugly Numbers
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 11933 Accepted: 5244

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
原题地址:http://acm.pku.edu.cn/JudgeOnline/problem?id=1338
________________________________________________________________________________________________________________________________________
题解:
暴力方法显然是要超时的。
这题显然用生成法,但是问题是如何判断大小关系。

 

3个指针,分别表示3个素数乘到哪了,然后通过比较3个指针位置的递推结果来确定下一个数是什么。注意重复数字。

 

代码:

 

代码
1 //设3个指针,分别表示3个素数乘到哪了,然后通过比较3个指针位置的递推结果来确定下一个数是什么。注意重复数字。
2  #include<stdio.h>
3  int ans[3000];
4  int i,p2,p3,p5,n,temp;
5  int min(int a,int b,int c)
6 {
7 if (a<b&&a<c)
8 {
9 p2++;
10 return a;
11 }
12 if (b<c)
13 {
14 p3++;
15 return b;
16 }
17 p5++;
18 return c;
19 }
20  int main()
21 {
22 p2=1;
23 p3=1;
24 p5=1;
25 ans[1]=1;
26 for (i=2;i<=1500;i++)
27 {
28 temp=ans[i-1];//去除重复数字
29 while (temp==ans[i-1])
30 temp=min(ans[p2]*2,ans[p3]*3,ans[p5]*5);
31 ans[i]=temp;
32 }
33 scanf("%d",&n);
34 while (n!=0)
35 {
36 printf("%d\n",ans[n]);
37 scanf("%d",&n);
38 }
39 return 1;
40 }
41

 

posted on 2010-07-28 12:54  风也轻云也淡  阅读(263)  评论(0编辑  收藏  举报