Factorial Trailing Zeroes

来源:互联网 发布:完整消防队源码 编辑:程序博客网 时间:2024/06/16 16:11

题目:

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

Note: Your solution should be in logarithmic time complexity.

乍一看,这确实不难,很简单的做法是先求n!嘛,然后求0的个数。结果是没问题,但是时间复杂度不符合要求,求n!就要O(n)的时间复杂度。

虽然说那样做不符合要求,但你稍微思考下,也轻松发现有更好的办法。0的个数跟有多少个10相乘有关,而要产生10,分解下就得有2和5,很容易发现,阶乘过程中,能分解成5的数一定比能分解成2的数要少。因此,就看n!能有多少个数可以分解成5的。

15! 中有3个5(15,10,5)
25!中有6个5(25,25,20,15,10,5)25中有两个5
代码如下:


0 0
原创粉丝点击