hoj1181,寻找丑数。
题意:把只具有素数因子2、3、5的数称为丑数;特别地,1也算做丑数。
把所有可能的丑数按从小到大的顺序排列。
例如:前11个丑数序列为1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...
要求输出第1500个丑数。
分析:采用动态规划的解法,初始时,设置三个指针p2,p3,p5。
计算三个指针指向的数分别乘以各自的因子2、3、5,取最小值作为下一个出现的元素,
同时更新三个指针的位置(要满足当前指针指向的数乘以各自的因子是第一个大于现有序列中最大丑数的条件)。
c代码:
#include<stdio.h>
#define SIZE 1501
long minn(int a,int b,int c){
int tmp;
tmp=a<b?a:b;
return tmp<c?tmp:c;
}
int main(){
long A[SIZE];
int pos,t2,t3,t5,i;
long MIN;
A[0]=1;
t2=t3=t5=0;
pos=1;
while(pos<1500){
MIN=minn(A[t2]*2,A[t3]*3,A[t5]*5);
A[pos++]=MIN;
if(A[t2]*2<=MIN)t2++;
if(A[t3]*3<=MIN)t3++;
if(A[t5]*5<=MIN)t5++;
}
/*for(i=0;i<pos;i++)printf("%d:%ld\n",i,A[i]);
printf("pos=%d\n",pos);*/
printf("The 1500\'th ugly number is %ld.\n",A[pos-1]);
return 0;
}