Factorial Trailing Zeroes - Math - Easy - LeetCode
💻 coding

Factorial Trailing Zeroes - Math - Easy - LeetCode

1 min read 149 words
1 min read
ShareWhatsAppPost on X
  • 1The number of trailing zeroes in n! is determined by the number of factors of 5 in the numbers from 1 to n.
  • 2The provided solution uses recursion to count the factors of 5, achieving a time complexity of O(n).
  • 3For any n, the trailing zeroes in n! can be calculated using the formula: n/5 + TrailingZeroes(n/5).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The number of trailing zeroes in n! is determined by the number of factors of 5 in the numbers from 1 to n."

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.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 1 October 2020 · 1 min read · 149 words

Part of AskGif Blog · coding

You might also like