172. Factorial Trailing Zeroes
2016-06-18 10:55
513 查看
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
分析摘自
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的次幂
public int trailingZeroes(int n) {
if(n<1) return 0;
int c = 0;
while(n/5 != 0) {
n /= 5;
c += n;
}
return c;
}
Note: Your solution should be in logarithmic time complexity.
分析摘自
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的次幂
public int trailingZeroes(int n) {
if(n<1) return 0;
int c = 0;
while(n/5 != 0) {
n /= 5;
c += n;
}
return c;
}
相关文章推荐
- daima
- XTUOJ1247 Pair-Pair 预处理+暴力
- 统计学、人工智能、机器学习、数据挖掘的区别与联系之(1) 概念
- rails安装
- hdu 1023 Train Problem II 卡特兰数
- Painy's World 重写以及 杀人速写重写
- Tensorflow 深度学习分布式实现方式
- AFN3.0 PATCH请求报错Error Domain=NSURLErrorDomain Code=-1012 "(null)"
- "围观"设计模式(22)--行为型之职责链模式(Chain Of Responsibility Pattern)
- http://blog.csdn.net/liuhe688/article/details/6733407
- 磁盘阵列RAID原理、种类及性能优缺点对比
- 服务器TIME_WAIT和CLOSE_WAIT详解和解决办法
- wait3,wait4 用法
- hdu 1021 Fibonacci Again(斐波那契数列,取余)
- 手贱装了win10之后用hotmail的邮箱登录了小娜
- 使用dd工具对磁盘RAID5和10进行I/O性能测试
- Lock wait timeout exceeded; try restarting transaction
- rails安装:gem更换成淘宝源
- LeetCode-217 Contains Duplicate
- Keychain简单存储(不使用官方封装)