【leetcode】Factorial Trailing Zeroes
Factorial Trailing Zeroes
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
统计末尾0的个数,只需要统计2,5的个数就可以了
1 class Solution { 2 public: 3 int trailingZeroes(int n) { 4 5 int count2=0; 6 int count5=0; 7 8 for(int i=2;i<=n;i++) 9 { 10 int num=i; 11 while(num%2==0&&num>0) 12 { 13 count2++; 14 num=num/2; 15 } 16 17 18 while(num%5==0&&num>0) 19 { 20 count5++; 21 num=num/5; 22 } 23 } 24 25 return min(count2,count5); 26 } 27 };
[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的上升,[n/2^p]会远大于[n/5^p]
因此左边的加和一定大于右边的加和,也就是n!质因数分解中,2的次幂一定大于5的次幂
(感谢陆草纯博主的证明)
5的个数显然要比2的个数多,所以只统计5的个数就可以了
1 class Solution { 2 public: 3 int trailingZeroes(int n) { 4 5 int count2=0; 6 int count5=0; 7 8 for(int i=2;i<=n;i++) 9 { 10 int num=i; 11 12 while(num%5==0&&num>0) 13 { 14 count5++; 15 num=num/5; 16 } 17 } 18 19 return count5; 20 } 21 };
既然只要统计5的个数就可以了,那么假设n=100,考虑有多少个5,
1~100里面有
1*5,2*5,3*5……20*5
通过上面的式子我们可以找到20个5
并且1-20之中也是存在5的,
1*5,2*5,3*5,4*5
又找到了4个5
而1-4之中就没有5了,因此共有24个5
可以抽象成下面的递归算法
1 class Solution { 2 public: 3 int trailingZeroes(int n) { 4 return get5(n); 5 } 6 7 int get5(int n) 8 { 9 if(n<5)return 0; 10 return n/5+get5(n/5); 11 } 12 };
分类:
算法研究
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!