动态规划,比较简单,直接参见下面的代码。 /*Ugly Numbers Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 13272 Accepted: 5856 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 New Zealand 1990 Division I,UVA 136 */ #include <stdio.h> #define MAX_NUM_OF_UNGLY_NUMBER 1501 int gaiUnglyNum[MAX_NUM_OF_UNGLY_NUMBER]; #define MIN(a,b) (((a) < (b)) ? (a) : (b)) #define THREE_MIN(a,b,c) MIN(MIN(a,b),c) int UglyNumbersmain(void) { int iLoop; int iLoop2 = 1; int iLoop3 = 1; int iLoop5 = 1; int iNthUgly; gaiUnglyNum[1] = 1; for (iLoop = 2; iLoop < MAX_NUM_OF_UNGLY_NUMBER; iLoop++) { while (gaiUnglyNum[iLoop2]*2 <= gaiUnglyNum[iLoop-1]) { iLoop2++; } while (gaiUnglyNum[iLoop3]*3 <= gaiUnglyNum[iLoop-1]) { iLoop3++; } while (gaiUnglyNum[iLoop5]*5 <= gaiUnglyNum[iLoop-1]) { iLoop5++; } gaiUnglyNum[iLoop] = THREE_MIN(gaiUnglyNum[iLoop2]*2,gaiUnglyNum[iLoop3]*3,gaiUnglyNum[iLoop5]*5); } while(1) { scanf("%d",&iNthUgly); if (0 == iNthUgly) { break; } printf("%d/n",gaiUnglyNum[iNthUgly]); } return 0; }