题目描述
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^x*3^y*5^z组成的,对于输入的n,所以可以对小于n的丑数进行排序,得到第n个丑数。
C++代码
1 #include <iostream> 2 #include <iomanip> 3 #define min(x,y) ((x)<(y)?(x):(y)) 4 using namespace std; 5 6 int a[1505]; 7 int num ; 8 void init() 9 { 10 int i1=1,i2=1,i3=1; 11 a[1] = 1; 12 int i ; 13 i = 2; 14 while(i <= 1500) 15 { 16 a[i] = min(min(a[i1] * 2 ,a[i2] * 3 ) ,a[i3] * 5 ); 17 while(a[i1] * 2 == a[i] ) i1 ++ ; 18 while(a[i2] * 3 == a[i] ) i2 ++ ; 19 while(a[i3] * 5 == a[i] ) i3 ++ ; 20 i ++ ; 21 } 22 } 23 int main() 24 { 25 int n ; 26 init(); 27 while(scanf("%d",&n)!=EOF && n != 0) 28 { 29 printf("%d\n",a[n]); 30 } 31 return 0; 32 }
时间复杂度不会分析。。。。求指导