问题描述:给定一个整数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);