Leetcode Note: Factorial Trailing Zeroes
I. Description
Given an integer n, return the number of trailing zeroes in n !.
Note: Your solution shocould be in logarithmic time complexity.
Ii. Question Analysis
The requirement of the question is to give an integern
, Find outn!
The end of the result is0
. The brute force law is obtained first.n!
And directly calculate the end0
. (Repeated (n !) /10, until the remainder is not 0), if the inputn
When the value is too large, it will cause overflow during factorial calculation, so this method is not easy to use.
Http://www.cnblogs.com/ganganloveu/p/4193373.html provides a very clever solution:
In fact, as longn
Factorialn!
, For factorization:n!=2^x*3^y*5^z*...
Apparently0
The number is equalmin(x,z)
And it is proved that the following information can be obtained:min(x,z)==z
.
For example:
n = 5
,5!
Prime factor decomposition:5! = 2 * 2 * 2 * 3 * 5
Contains3
Items2
,1
Items3
And1
Items2
. Suffix0
The number is1
.
n = 11
,11!
Prime factor decomposition:11! = 2^8 * 3^4 * 5^2 * 7
Contains8
Items2
,4
Items3
And2
Items5
. Suffix0
The number is2
.
Proof:
For factorial, that is1*2*3*...*n
, Set[n/k]
Representative1~n
Number of divisible by k
Apparently,[n/2] > [n/5]
(The left side is Feng2
Add1
On the right side5
Add1
)
[n/2^2] > [n/5^2]
(The left side is Feng4
Add1
On the right side25
Add1
)
......
[n/2^p] > [n/5^p]
(The left side is Feng2^p
Add1
On the right side5^p
Add1
)
With powerp
Appears2^p
The probability is much higher than that of appearance.5^p
.
Therefore, the addition on the left must be greater than the addition on the right, that isn!
Prime factor decomposition,2
The power must be greater5
Power.
Iii. Sample Code
#include
using namespace std;class Solution{public: int trailingZeroes(int n) { int result = 0; while (n) { result += n / 5; n /= 5; } return result; }};
Iv. Summary
There are few codes for this question, but it is necessary to deduce the complex requirements from the question into simple operations. In general, it still takes some effort.