zoukankan      html  css  js  c++  java
  • 172. Factorial Trailing Zeroes java solutions

    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.

    Subscribe to see which companies asked this question

     1 public class Solution {
     2     public int trailingZeroes(int n) {
     3         int count = 0;
     4         while(n > 0){
     5            count += n/5;
     6            n /= 5;
     7         }
     8         return count;
     9     }
    10 }

    对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的次幂

  • 相关阅读:
    kafka学习(八)
    kafka学习(七)
    kafka学习(六)
    kafka学习(五)
    kafka学习(四)
    kafka学习(三)
    kafka学习(二)
    kafak学习(一)
    ssh远程登录
    pycharm
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5461842.html
Copyright © 2011-2022 走看看