LeetCode172. Factorial Trailing Zeroes

本文介绍了一种高效算法来计算给定整数n的阶乘(n!)末尾0的数量,并通过逐步优化实现了对数时间复杂度的要求。最终算法通过对n进行一系列除以5的操作并累加结果来得出答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.

题目中要求计算n!末尾0的个数,最笨的方法莫过于首先计算n!,然后再计算结果末尾的0,这样时明显不符合题目算法时间复杂度要求的。

我们首先看N比较小的一种情况,6!= 1x2x3x4x5x6 = 144 5 = 720 这里面末尾只有一个0,是由5x偶数得到的。同样10!= 6! 7 * 8 9 *10 = 144 5* 7 8 *9 (5 *2) 有两个5,我们可以认为阶乘末尾的0是由于5乘以偶数决定的。而且在阶乘中偶数数量远大于5的个数,那么阶乘末尾的0是有5的个数决定的。所以我们有了下面这段的代码:

    int count_5(int n){
        int result = 0;
        while(n>0 && n%5 == 0){
            result++;
            n = n/5;
        }
        return result;
    }

    int trailingZeroes(int n) {
        int result = 0;
        for(int i=1; i<=n; i++){
            if(i%5 == 0){
                result += count_5(i);
            }
        }
        return result;
    }

count_5计算整数n的可以分解得到多少个5,很可惜这段代码超时了。

继续分析,
n=10的情况下,只有5、10两个元素产生0,
n = 20情况下,有5、10、15、20是个元素产生0
n= 30情况下,有5、10、15、20、25、30六个元素产生0,而且25=5*5 可以产生2个0
同样50、75、100均能产生2个0,
而125= 5*5*5能够产生3个0
这样我们得到
f(n) = sum(n/5, n/25, n/125…)

代码如下:

class Solution {
public:
    int trailingZeroes(int n) {
        int result = 0;
        while (n ) {
            n = n / 5;
            result += n;
        }
        return result;
    }
};

wiki Trailing zero

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值