[解题报告]136 - Ugly Numbers
Ugly Numbers |
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, 15, ...
shows the first 11 ugly numbers. By convention, 1 is included.
Write a program to find and print the 1500'th ugly number.
Input and Output
There is no input to this program. Output should consist of a single line as shown below, with <number> replaced by the number computed.
Sample output
The 1500'th ugly number is <number>.
记住题目对丑陋数的定义是其基本因子有且只能有2,3,5组成,就是说2*3*5*7=210就不是丑陋数
那么如何得出丑陋数数列?
要得出第N项,就得在前N-1项中扫描,把所有的N-1项乘以2,3,5.然后乘完得到的结果比N-1大且最小的那个就是N
#include<stdio.h> int main() { int ugly_number[1505] = {1}; int n2=0,n3=0,n5=0; int i; for(i=1;i<1500;i++) { for(;n2<i;n2++) if(ugly_number[n2]*2>ugly_number[i-1]) break; for(;n3<i;n3++) if(ugly_number[n3]*3>ugly_number[i-1]) break; for(;n5<i;n5++) if(ugly_number[n5]*5>ugly_number[i-1]) break; ugly_number[i]=min(ugly_number[n2]*2,ugly_number[n3]*3); ugly_number[i]=min(ugly_number[i],ugly_number[n5]*5); } printf("The 1500'th ugly number is %d.\n",ugly_number[1499]); return 0; } int min(int a,int b) { return a>b?b:a; }