Math172FactorialTrailingZeroes

来源:互联网 发布:手机桌面图标软件 编辑:程序博客网 时间:2024/06/03 07:28

思路

  • I think about 2*5 and 10 can create 10, but I ignore all 10 are also realted with 5, which means if 10%5 == 0, then one trailing 0 will be created.
  • I do think we need 5 and even number, and even number is always ample because every two even comes a 5 or 10
  • 正确思路

    Because all trailing 0 is from factors 5 * 2.


But sometimes one number may have several 5 factors, for example, 25 have two 5 factors, 125 have three 5 factors. In the n! operation, factors 2 is always ample. So we just count how many 5 factors in all number from 1 to n.
  • 在11/20/2016的solution里面, 有溢出问题值得探讨Failed Case: 1808548329
    • https://discuss.leetcode.com/topic/6899/failing-test-case-1808548329
    • http://stackoverflow.com/questions/27785724/trailing-zeroes-of-a-factorial
    • Your problem is that once divider gets large enough (more than Integer.MAX_INT / 5) then the line divider*=5; causes divider to overflow to the “wrong” value. The value in question is 5 to the 14th power, which is 6103515625, but which overflows to 1808548329.

计算复杂度

这个讲解很好https://discuss.leetcode.com/topic/6848/my-explanation-of-the-log-n-solution
* Q:can u explain why is this solution log(n) instead of O(n)?
* A: any time your solution is reducing by a factor greater than 1 it is log time with the log base being your factor. In this case you are reducing by a factor of 5 each loop so you have O(log5 N) <- that is meant to be “log N with base 5”. You could be reducing by a factor of 2 or 10 or 50 that is still log time.

0 0
原创粉丝点击