求n的阶乘末尾有几个零

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ccutsoft20144264/article/details/51534838


通过因数分解知道,10是由2和5相乘得到的,而在n的阶乘中,因子2的数目总是比5多的,所以最终末尾有几个零取决于其中有几个5。1到n中能够整除5的数中有一个5,能整除25的数有2个5(且其中一个在整除5中已经计算过)…... 所以只要将n不断除以5后的结果相加,就可以得到因子中所有5的数目,也就得到了最终末尾零的数目,时间复杂度log(n)。


code:

#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
	int n,cnt;
	while(cin>>n)
	{
		cnt=0;
		while(n)
		{
			n/=5;
			cnt+=n;
		}
		cout<<cnt<<endl;
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/ccutsoft20144264/article/details/51534838