POJ 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.
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
题目的意思大概就是:丑数是只能被2,3,5整除的数 (1也包括),把丑数从小到大排好顺序,组成数列,输入一个数n,输出这个数列的第n个数。
但是要注意到数的范围是1500,一开始我就用的是最简单的,把每个数一直除以2再除以3再除以5来验证是否只能被2,3,5整除,但是很显然时间超限的。于是就换了一种做法。新做法的思路是:把1500个丑数存起来,直接输出。如何找出丑数呢,把已经找到的数分别乘以2,3,5取最小的一个作为新数(因为要求小到大排列的)
1 #include<stdio.h> 2 int min(int a,int b,int c) 3 { 4 if(a > b)a = b; 5 if(a > c)a = c; 6 return a; 7 } 8 9 int main() 10 { 11 int a[1500]; 12 a[0]=1; 13 int j,i; 14 int temp1,temp2,temp3; 15 for( i=1;i <= 1499;i++) 16 { 17 for(j = 0;j <= i - 1;j++) 18 if(a[j]*2>a[i-1])//新数一定要比旧的数大,所以要一直找的大的数才能记录下来 19 { 20 temp1=a[j]*2; 21 break; 22 } 23 for(j = 0;j <= i - 1;j++) 24 if(a[j]*3>a[i-1]) 25 { 26 temp2=a[j]*3; 27 break; 28 } 29 for(j = 0;j <= i - 1;j++) 30 if(a[j] * 5 > a[i-1]) 31 { 32 temp3 = a[j]*5; 33 break; 34 } 35 a[i]=min(temp1,temp2,temp3);//记录下的三个数取最小的 36 } 37 while(i != 0)//以零为结尾的输出 38 { 39 scanf("%d",&i); 40 if(i != 0) 41 printf("%d\n",a[i-1]); 42 } 43 return 0; 44 }