LeetCode: Factorail Trailling zeros

Problem statements:

Follow up Questions:

Problem Analysis:

Ease cases to consider:

This tabe represents the transition of triling zeros .

n Zeros in n! n Zeros in n! n Zeros in n! n Zeros in n! n Zeros in n!
1 0 11 2 21 4 31 7 41 9
2 0 12 2 22 4 32 7 42 9
3 0 13 2 23 4 33 7 43 9
4 0 14 2 24 4 34 7 44 9
5 1 15 3 25 6 35 8 45 10
6 1 16 3 26 6 36 8 46 10
7 1 17 3 27 6 37 8 47 10
8 1 18 3 28 6 38 8 48 10
9 1 19 3 29 6 39 8 49 10
10 2 20 4 30 7 40 9 50 12

Solution Approach:

Brute-Force Approach (and why it fails):






    /**
    * Brueforce solution
    *
    * @param n
    * @return
    */
    public int bruteForceSolution(int n) {
      int f = calculateFactorial(n);

      int count = 0;

      while (f % 10 == 0) {
        ++count;
        f /= 10;
      }
      return count;
    }

    /**
    * Calculate factorial.
    *
    * @param n
    */
    private int calculateFactorial(int n) {
      if (n < 1) {
        return 1;
      }
      return n * calculateFactorial(n - 1);
    }

Optimal Soluion





  /**
   * Optimal Logarithmic solution log base 5 (n)
   *
   * @param n
   * @return
   */
  public int logrithmicSolution(int n) {
    int count = 0;
    while(n >= 5) {
      count += n / 5;
        n = n / 5;
    }
    return count;
  }
  /**
   * Optimal Logarithmic solution log base 5 (n)
   *
   * @param n
   * @return
   */
  public int logrithmicSolution(int n) {
      int count = 0;
      int pof = 5;
      while(n >= pof) {
          count += n / pof;
          pof *= 5;
      }
      return count;
  }

------ End of document------