LeetCode:Factorial Trailing Zeroes

本文介绍了一种高效计算n!尾部0的数量的方法。通过分析2与5在阶乘中的分布规律,得出结论:尾0数量等同于5的倍数出现的次数。并提供了一个简洁的C++实现。

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

Factorial Trailing Zeroes

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

Note: Your solution should be in logarithmic time complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

 借鉴别人的  http://www.cnblogs.com/ganganloveu/p/4193373.html 代码简洁高效

 

对n!做质因数分解n!=2x*3y*5z*...

显然0的个数等于min(x,z),并且min(x,z)==z

证明:

对于阶乘而言,也就是1*2*3*...*n
[n/k]代表1~n中能被k整除的个数
那么很显然
[n/2] > [n/5] (左边是逢2增1,右边是逢5增1)
[n/2^2] > [n/5^2](左边是逢4增1,右边是逢25增1)
……
[n/2^p] > [n/5^p](左边是逢2^p增1,右边是逢5^p增1)
随着幂次p的上升,出现2^p的概率会远大于出现5^p的概率。
因此左边的加和一定大于右边的加和,也就是n!质因数分解中,2的次幂一定大于5的次幂

 1 class Solution {
 2 public:
 3     int trailingZeroes(int n) {
 4         int result=0;    
 5         while(n)
 6         {
 7             result+=n/5;
 8             n/=5;
 9         }
10         return result;
11         
12     }
13 };

 

转载于:https://www.cnblogs.com/xiaoying1245970347/p/4615510.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值