n!后面有多少个0 | 
|||
  | 
|||
description | 
|||
从输入中读取一个数n,求出n!中末尾0的个数。  | 
|||
input | 
|||
输入有若干行。第一行上有一个整数m,指明接下来的数字的个数。然后是m行,每一行包含一个确定的正整数n,1<=n<=1000000000。  | 
|||
output | 
|||
对输入行中的每一个数据n,输出一行,其内容是n!中末尾0的个数。  | 
|||
sample_input | 
|||
3 3 100 1024  | 
|||
sample_output | 
|||
0 24 253  | 
思路:
n!的素因子分解中素数p的幂为: [n/p]+[n/p^2]+[n/p^3]+……
证明在http://www.cnblogs.com/openorz/archive/2011/11/14/2248992.html详述
从公式可以易看出n!的素因子p的幂随p增大而递减
对于此题,可以知道末尾的0只有素因子2*5产生,且2的幂一定比5大,所以产生0的个数等于(2,5)的匹配数,也就是5的素因子个数
用结论公式可以O(logn)解决。
//Accepted 820k 2ms C++ (g++ 3.4.3) 331  
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int n;
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        int ans=0;
        int p=5;
        while(n/p) ans+=n/p,p*=5;
        printf("%d\n",ans);
    }
    return 0;
}
NEFU 118 n!后面有多少个0 (n!的素因子幂问题)
原文:http://blog.csdn.net/kalilili/article/details/44852495