Title Description:
Given an integer n, return the number of trailing zeroes in N!.
Note:your solution should is in logarithmic time complexity.
Problem Solving Ideas:
For factorial, that is 1*2*3*...*n
[N/k] Represents the number of 1~n that can be divisible by k
Well, obviously,
[N/2] > [N/5] (on the left is 2 increase 1, the right is 5 increase 1)
[N/2^2] > [n/5^2] (on the left is 4 increase 1, the right is 25 increase 1)
......
[N/2^p] > [N/5^p] (on the left is the 2^p increase 1, on the right is every 5^p 1)
With the rise of power p, the probability of appearing 2^p is much greater than the probability of 5^p.
So the left side of the addition and must be greater than the right side of the sums, that is, n! quality factor decomposition, 2 power must be greater than the power of 5
The code is as follows:
public class Solution {public int trailingzeroes (int n) { int res = 0; while (n > 0) { res + = N/5; n/= 5; } return res; }}
Java [Leetcode 172]factorial Trailing Zeroes