POJ 1401 Factorial

题意:求一个数的阶乘最后边有几个0。

解法:如果有0说明这个数含有2和5这两个因子,对于一个阶乘来说因子2的数量一定比5的数量多,所以只要算有几个5就可以了,依次算5的个数,25的个数,125的个数……n以下的数字里含有因子5的数的个数是⌊n / 5⌋,含有因子25的数的个数是⌊n / 25⌋,以此类推,但是不需要因为25是平方就乘2,只要加上这个数就可以了,因为算5的时候已经数过一次25了。

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<math.h>
#include<limits.h>
#include<time.h>
#include<stdlib.h>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<vector>
#define LL long long
using namespace std;
int solve(int n)
{
    int res = 0;
    LL base = 5;
    while(base <= 1000000000)
    {
        res += n / base;
        base *= 5;
    }
    return res;
}
int main()
{
    int T;
    while(~scanf("%d", &T))
    {
        while(T--)
        {
            int n;
            scanf("%d", &n);
            printf("%d
", solve(n));
        }
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/Apro/p/4849085.html