您的位置:首页 > 其它

(ACM数论)求N的阶乘末尾有多少个0

2016-08-29 16:23 232 查看
问题描述:给定一个整数N,那么N的阶乘N!末尾有多少个0?

这个问题的难点在于,不能直接计算出N!,因为会溢出。

既然不能直接计算,那就换个姿势计算(手动滑稽)

首先,我们考虑到N!末尾0的个数和 N!有多少个因子10有关,而10 = 2 * 5 ,于是我们得到了一个解法:

把2,3,… ,N每个数拥有因子2的个数累加起来记为countTwo,把2,3,… ,N每个数拥有因子5的个数累加起来记为countFive,问题的答案则为min(countTwo, countFive)

代码如下:

int countTwo = 0, countFive = 0;
for(int i = 2 ; i <= N ; i++)
{
int tmp = i;//每个数
while(tmp % 2 == 0)
{
tmp = tmp / 2;
countTwo++;
}
while(tmp % 5 == 0)
{
tmp = tmp / 5;
countFive++;
}
}
//min(countTwo,  countFive)
printf("ans = %d\n",
countFive < countTwo ? countFive :countTwo);


输入不同的N可以发现,countFive 必然小于 countTwo,这是由于:5^n > 2^n,即每有一个因子5,就必定会有一个因子2。

所以解法可以改为把2,3,… ,N每个数拥有因子5的个数累加起来记为countFive,问题答案为countFive,代码如下:

int countFive = 0;
for(int i = 5 ; i <= N ; i++)
{
int tmp = i;//每个数
while(tmp % 5 == 0)
{
tmp = tmp / 5;
countFive++;
}
}
printf("ans = %d\n", countFive);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm