/*
Ugly numbers are numbers whose only prime factors are 2,3or 5.
The sequence 1,2,3,4,5,6,8,9,10,12,15,…shows the first 11ugly numbers.
By convention,1 is included.
Write a time efficient program to find and print the 1500'th ugly number.(20 points)
*/
#include <stdio.h>
int cal_num(int seq);
int cal_num(int seq)
{
int i,j;
int cnt;
int temp;
cnt = 0;
j = 0;
while(1)
{
j++;
i = j;
if(i == 1)
{
cnt++;
printf("%d:%d\n",cnt,j);
if(cnt == seq)
{
return j;
}
}
else
{
while(i % 2 == 0)
{
if(i /2 == 1 )
{
cnt++;
printf("%d:%d\n",cnt,j);
if(cnt == seq)
{
return j;
}
else
{
break;
}
//i = 1;
}
else
{
i = i / 2;
}
}
while((i % 3 == 0))
{
if(i / 3 == 1 )
{
cnt++;
printf("%d:%d\n",cnt,j);
if(cnt == seq)
{
return j;
}
else
{
break;
}
}
else
{
i = i / 3;
}
}
while(i % 5 == 0)
{
if(i / 5 == 1 )
{
cnt++;
printf("%d:%d\n",cnt,j);
if(cnt == seq)
{
return j;
}
else
{
break;
}
}
else
{
i = i / 5;
}
}
}//end else
}
return ;
}
int main(void)
{
int num;
num = cal_num(1500);
printf("num:%d\n",num);
return 0;
}
此程序还可以进一步完善,哪些方面呢?
1.基本元素的个数,更加灵活,
2.输出第n个元素,也可以更加灵活
3封装函数与设计API
文章评论(0条评论)
登录后参与讨论