C语言编程:100!的末尾有多少个零

100!的末尾有多少个零?

  • 问题分析:
    因为计算机所能表示的整数范围有限,所以无法直接通过计算获得结果,因此只能间接通过其他方法计算.

  • 算法设计:
    为了解决这个问题,必须首先从数学上分析在100!结果值的末尾产生零的条件:一个整数若含有因子25,则必然会在求100!是产生一个零.
    因此问题转换为1~100咋这100个整数中包含了多少个2
    5因子.又因为100个整数中2的因子远比5的因子多,则求出这100个整数中又多少个因子5,即可得出结果.
    若整数N能被25整除,则N包含2个因子5,若整数N能被5整除,则N包含1个因子5.

  • 程序示例:

#include <stdio.h>

int main ( )
{
	int num,count = 0;
	for (num = 1; num <= 100; num++)
	{
		if(num%5 == 0)
		{
			count++;
		}
		if(num%25 == 0)
		{
			count++;
		}		
	}
	printf("The number of 0 in the end of 100! is :%d\n", count);
	
	return 0;
}
  • 运行结果如下:
The number of 0 in the end of 100! is :24
  • 问题进一步分析:
    上述示例存在明显缺点,程序中判断N包含多少个因子5的方法是与题目中的100有关的,若题目中的100该为1000,则就要修改程序中求因子5 的算法
  • 程序示例:
#include <stdio.h>

int main ( )
{
	int num,count = 0;
	for (num = 1; num <= 1000; ++num)
	{
		if(num%5 == 0)
		{
			count++;
		}
		if(num%25 == 0)
		{
			count++;
		}	
		if(num%125 == 0)
		{
			count++;
		}	
		if(num%625 == 0)
		{
			count++;
		}	

	}
	printf("The number of 0 in the end of 100! is :%d\n", count);
	return 0;
}
  • 输出结果:
The number of 0 in the end of 100! is :249
  • 思考:
    修改程序中求因子5的算法,使程序可以求出任意N!的末尾有多少个零.
  • 程序示例:
#include <stdio.h>

int main()
{
	int n, count = 0;

	printf("Please input any integer:");
	scanf("%d",&n);
	while(n)
	{
		n /= 5;
		count += n;
	}
	printf("The number of 0 in the end of %d! is %d.\n", n, count);
	
	return 0;
}
  • 输出结果:
Please input any integer:100
The number of 0 in the end of 0! is 24.
Please input any integer:1000
The number of 0 in the end of 0! is 249.
  • 9
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bill_Hao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值