求阶乘位数0的个数
例如:
求:100!的末尾有多少个0
分析:显然100!的位数超出已知基本数据类型的范围,所以不能单纯的先求取出100!的数值,再判断末尾有多少个0.寻找规律可以发现,该问题可以转换成1~100的100个整数一共有多少个因数5,的问题。
程序如下:
#include <stdio.h>
int main()
{
int i;
int num = 0;
for(i = 5;i <= 100;i = i + 5)
{
num ++;
if(i % 25 == 0)
{
num ++;
}
}
printf("The number of 0 in the end of 100! is %d\n",num);
return 0;
}
调试结果如下:
The number of 0 in the end of 100! is 24
那要求1000!的位数有几个0又应该怎么办?
例程:
#include <stdio.h>
int main()
{
int i;
int num = 0;
for(i = 5;i <= 1000;i = i + 5)
{
num ++;
if(i % 25 == 0)
{
num ++;
if(i % 125 == 0)
{
num ++;
if(i % 625 == 0)
{
num ++;
}
}
}
}
printf("The number of 0 in the end of 1000! is %d.\n",num);
return 0;
}
调试结果为:
The number of 0 in the end of 100! is 24
例程:
#include <stdio.h>
int main()
{
int i;
int n;
int m;
int flag;
int num = 0;
printf("Please input the number:\n");
scanf("%d",&n);
if(n >= 0 && n <= 4)
{
num = 0;
}
else
{
for(i = 5;i <= n;i = i + 5)
{
m = 5;
flag = 1;
while(flag == 1)
{
if(i % m == 0)
{
num ++;
m = 5 * m;
}
else
{
flag = 0;
}
}
}
}
printf("The number of 0 in the end of %d! is %d.\n",n,num);
return 0;
}
[root@localhost funny]# cat weishu_plus.c
//求100!的末尾的0的个数
#include <stdio.h>
int main()
{
int i;
int num = 0;
for(i = 5;i <= 100;i = i + 5)
{
num ++;
if(i % 25 == 0)
{
num ++;
}
}
printf("The number of 0 in the end of 100! is %d\n",num);
return 0;
}
调试结果为:
Please input the number:
4
The number of 0 in the end of 4! is 0.
Please input the number:
5
The number of 0 in the end of 5! is 1.
Please input the number:
100
The number of 0 in the end of 100! is 24.
Please input the number:
1000
The number of 0 in the end of 1000! is 249.
Please input the number:
555
The number of 0 in the end of 555! is 137.