题目描述
如果一个数的素因子只包含2,3,5或7,那么我们把这种数叫做丑数。序列1,2,3,4,5,6,7,8,9,10,12,14,15,16,18,20,21,24,25,27...展示了前20个丑数。
请你编程寻找这个序列中的第n个元素。
输入
输入包含多组测试数据。每组输入为一个整数n(1<=n<=5842),当n=0时,输入结束。
输出
对于每组输入,输出一行“The nth humble number is number.”。里面的n由输入中的n值替换,“st”,“nd”,“rd”和“th”这些序数结尾的用法参照输出样例。
样例输入
1
2
3
4函数功能:把这个数进行分解质因数,并判断它的所有质因数是否只有2357
11
12
13
21
22
23
100
1000
5842
0
样例输出
The 1st humble number is 1.
The 2nd humble number is 2.
The 3rd humble number is 3.
The 4th humble number is 4.
The 11th humble number is 12.
The 12th humble number is 14.
The 13th humble number is 15.
The 21st humble number is 28.
The 22nd humble number is 30.
The 23rd humble number is 32.
The 100th humble number is 450.
The 1000th humble number is 385875.
The 5842nd humble number is 2000000000.
【思路】:用暴力枚举法--当加到这个数的时候,对这个数惊醒分解质因数--并判断它的质因数是否全部为2,3,5,7
如果是:则count++ ---知道n==count时,输出此时的数i;
如果不是:接着下一次循环即可;
【C源程序如下】:
#include#includeint ll(int n);
int main()
{
int n,c=1,i,y;
double x=0;
do{
scanf("%d",&n);
x=0;c=1;
if(n==0) exit(0);
if(n==1) x=1;
else
{
for(i=2;;i++)
{
y=ll(i);
if(y!=1)
{
c++;
}
if(c==n)
{
x=i;
break;
}
}
}
if(n==1||n==21)
printf("The %dst humble number is %.0lf.\n",n,x);
if(n==2||n==22||n==5842)
printf("The %dnd humble number is %.0lf.\n",n,x);
if(n==3||n==23)
printf("The %drd humble number is %.0lf.\n",n,x);
if(n==4||n==11||n==12||n==13||n==100||n==1000)
printf("The %dth humble number is %.0lf.\n",n,x);
}while(n!=0);
return 0;
}
/*函数功能:把这个数进行分解质因数,并判断它的所有质因数是否只有2,3,5,7*/
int ll(int n)
{
int k=2,j=0,m;
int a[10000];
while(n>=k)//此时直接从2开始,在主函数中有对1的判断
{
if(n%k==0)
{
a[j]=k;//把输出的质因数存入数组中
n=n/k;
k=2;//将n重新赋值成2,因为分解的质因数中有可以重复的质因数
j++;
}
else
{
k++;
}
}
int find=0;
for(m=0;m<=j-1;m++)
{
if(a[m]!=2&&a[m]!=3&&a[m]!=5&&a[m]!=7)
find=1;//等于1表示不是丑数
}
return find;
}
这种方法我都为计算机感到忧伤(是计算机麻烦啊),它要进行太多从头开始的循环(但好在思路简单)
但原谅我没想到其他的方法
希望各位小可爱们知道的一起评论学习啊 拜托了0