Factorial Trailing Zeroes

来源:互联网 发布:鲁迅文学院2017网络班 编辑:程序博客网 时间:2024/06/11 16:24

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

Note: Your solution should be in logarithmic time complexity.

思路:尾部要出现是0的话,只有2和5相乘才会出现0,只有算出n!的因子中有多少个2*5就可以知道尾部有多少个0了,很显然n!中5的个数少于2的个数,所以只要算出n!中有多少个5相乘就可以了。1*2*3……*n中,5可以贡献出1个5,25=5*5可以贡献出两个5, 125=5*5*5可以贡献出3个5,先计算出5的倍数有多少个(n/5),其中每一个可以先贡献出一个5,注意诸如25,50,75,100等等之类的,由于这些数作为5的倍数已经先贡献出1个5,但是由于是25(25=5*5)的倍数还可以贡献出1个5,接下来计算25的倍数有多少个,即n/25,再可以贡献出一个5,由于125=5*5*5,可以贡献出3个5,但是125作为5和25的倍数已经预先贡献出了两个五,那么125的倍数还可以贡献出1个5,计算出125的倍数即可,即(n/125)....依次进行下去,直到5^x大于等于n。

注意:下面的算法会超时,可能是因为万一n很大,循环中x在不断增大,那么两个大数相除所用的时间会特别长,才会导致超时。

public class Solution {    public int trailingZeroes(int n) {        int x = 5;          int res = 0;          while(n >= x) {              res = res + n/x;              x = x*5;          }          return res;    }}


下面的算法可以AC通过。

public class Solution {    public int trailingZeroes(int n) {        int res=0;        if(n==0) return 0;        while(n>0)       {           res=res+n/5;           n=n/5;       }      return res;    }    }


0 0