Two Classic Factorial Problems on LeetCode
This article will resolve
| LeetCode | Difficulty |
|---|---|
| 172. Factorial Trailing Zeroes | 🟠 |
| 793. Preimage Size of Factorial Zeroes Function | 🔴 |
Prerequisite Knowledge
Before reading this article, you should first learn:
Factorial-related problems often appear in written tests. Today, we will discuss two of the most common ones:
1. Given a non-negative integer n, calculate how many zeros are at the end of the factorial n!.
This is also LeetCode Problem 172 "Factorial Trailing Zeroes". For example, if the input is n = 5, the algorithm returns 1 because 5! = 120 has one trailing zero.
The function signature is as follows:
int trailingZeroes(int n);2. Given a non-negative integer K, calculate how many n have exactly K trailing zeros in their factorial n!.
This is also LeetCode Problem 793 "Preimage Size of Factorial Zeroes Function". For example, if the input is K = 1, the algorithm returns 5, because there are 5 factorials (5!, 6!, 7!, 8!, 9!) with exactly one trailing zero.
The function signature is as follows:
int preimageSizeFZF(int K);I group these two problems together because they share commonalities. Let's analyze them one by one.