zoukankan      html  css  js  c++  java
  • [LeetCode#172]Factorial Trailing Zeroes

    Problem:

    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.

    Analysis:

    The mathematical problem is always so tricky and easy, as long as you master the inherent theory behind it.
    Reference:
    https://en.wikipedia.org/wiki/Trailing_zero
    Theory:
    The number of trailing zeros in the decimal representation of n!, the factorial of a non-negative integer n, is simply the multiplicity of the prime factor 5 in n!.
    http://bookshadow.com/weblog/2014/12/30/leetcode-factorial-trailing-zeroes/
    
    Reason: 
    The trailing zeros were actually caused by the 10 (which the the muliplicity of prime 5 and prime 2). And 
    n = 5: There is one 5 and 3 2s in prime factors of 5! (2 * 2 * 2 * 3 * 5). So count of trailing 0s is 1.
    n = 11: There are two 5s and three 2s in prime factors of 11! (2 8 * 34 * 52 * 7). So count of trailing 0s is 2.
    
    The number of 2s in prime factors is apparenlty equal or larger than that of 5s in prime factors. Thus we only need to count the number of 5s.
    Note: how to covert the equation(algorithm into program)!
    
    
    The magic characteristics behind prime factors:
    When we represent an integer into the prime factors form. 
    1. The form must be unique. (since no prime factor is divideable)
    2. We can gain some useful information from the prime factors. (like the number of trailing zero).

    Solution:

    public class Solution {
        public int trailingZeroes(int n) {
            int total = 0;
            while ( n / 5 != 0) {
                total += n / 5;
                n = n / 5;
            }
            return total;
        }
    }
  • 相关阅读:
    教育单元测试mock框架优化之路(下)
    教育单元测试mock框架优化之路(中)
    教育单元测试mock框架优化之路(上)
    spring /spring boot中mock
    Multi-Projector Based Display Code ------- Home
    投影的一些链接
    香茅油:不只是驱虫剂 new
    python特定时间发送消息到微信公众号
    基金定投研究
    PE就是市盈率的缩写 PB是平均市净率的缩写
  • 原文地址:https://www.cnblogs.com/airwindow/p/4774319.html
Copyright © 2011-2022 走看看