求阶乘的位数和后缀0个数


结合两个公式,斯特林公式 和 后缀0个数

#include<stdio.h>

#include<string.h>
#include<cmath>
using namespace std;

const double PI=3.14159265;

// 斯特林公式, 求总位数
int striling(int n) {
    double sum=(n*log(n) - n + 0.5*log(2*n*PI))/log(10)+1;
//    printf("%d\n",(int)sum);
    return int(sum);
}

// 后缀0个数
// https://leetcode-cn.com/problems/factorial-trailing-zeroes/solution/jie-cheng-hou-de-ling-by-leetcode/
int trailingZeroes(int n) {
    int zeroCount = 0;
    while (n > 0) {
        n /= 5;
        zeroCount += n;
    }
    return zeroCount;
}


int main()
{
    int n;
    while(scanf("%d", &n)==1)
    {
        int len=striling(n);
        int zeros=trailingZeroes(n);
//        printf("%d\n",zeros);
        printf("%d\n",len-zeros);
    }
}


两个相减,就是前缀部分
https://zh.wikipedia.org/wiki/%E6%96%AF%E7%89%B9%E9%9D%88%E5%85%AC%E5%BC%8F
https://leetcode-cn.com/problems/factorial-trailing-zeroes/solution/jie-cheng-hou-de-ling-by-leetcode/



posted on 2020-08-06 16:06  katago  阅读(211)  评论(0编辑  收藏  举报