求N!中末尾有几个0:
计算含因子2和5的对数
[table]
|1。。.N有几个2:
|N/2+N/4+N/8。。。。。
|1....N有几个5:
|N/5+N/25+N/125。。。。。。
[/table]
计算含因子2和5的对数
[table]
|1。。.N有几个2:
|N/2+N/4+N/8。。。。。
|1....N有几个5:
|N/5+N/25+N/125。。。。。。
[/table]
#include <stdio.h>
#include <stdlib.h>
int count(int n,int bot)
{
int cnt=0;
while(n/bot!=0)
{
cnt+=n/bot;
bot*=bot;
}
return cnt;
}
int main()
{
int n,cnt2,cnt5;
scanf("%d",&n);
cnt2=count(n,2);
cnt5=count(n,5);
unsigned long long sum=1;
for(unsigned int i=n;i>=1;--i)
{
sum*=i;
}
fprintf(stdout,"n!=%llu\n",sum);
fprintf(stdout,"zero counts:%d\n",cnt2<cnt5 ? cnt2:cnt5);
return 0;
}
本文介绍了一种计算N!中末尾0的数量的方法。通过分别统计从1到N的整数中因子2和5的个数来确定尾0的数量。代码使用C语言实现,并通过用户输入的N值进行计算,最后输出阶乘结果及尾0数量。

被折叠的 条评论
为什么被折叠?



