AAlgoLoopSpaced repetition for LeetCode
MEDIUMMath / Number TheoryLeetCode ↗

Factorial Trailing Zeroes

The key idea

A trailing zero comes from a factor of 10 = 2 x 5. In n! factors of 2 are far more common than factors of 5, so the count of trailing zeros equals the count of factor 5s. Count them by summing n//5 + n//25 + n//125 + ... until the divisor exceeds n.

Problem

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

Recall that n! = n x (n - 1) x (n - 2) x ... x 2 x 1 and by convention 0! = 1.

The follow-up asks for a solution that runs in logarithmic time.

Constraints

Examples

Input: n = 3 Output: 0
Input: n = 5 Output: 1
Input: n = 0 Output: 0

Complexity

Time: O(log n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Math / Number Theory problems