Blogs Hub

Factorial Trailing Zeroes - Math - Easy - LeetCode - MiniTV

Factorial Trailing Zeroes - Math - Easy - LeetCode - मिनी टीवी

Given an integer n, return the number of trailing zeroes in n!.

Follow up: Could you write a solution that works in logarithmic time complexity?

 

Example 1:

Input: n = 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:

Input: n = 5
Output: 1
Explanation: 5! = 120, one trailing zero.
Example 3:

Input: n = 0
Output: 0
 

Constraints:

1 <= n <= 104

public class Solution {
    public int TrailingZeroes(int n) {
        if(n==0){
            return 0;
        }        
        return n/5 + TrailingZeroes(n/5);
    }
}

Time Complexity: O(n)

Space Complexity: O(1)

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 numbers from 1 to n.