CSES Trailing Zeros 題解
題目
- Time limit: 1.00 s
- Memory limit: 512 MB
Your task is to calculate the number of trailing zeros in the factorial n!.
For example, and it has trailing zeros.
| Input | Output |
|---|---|
| The only input line has an integer . | Print the number of trailing zeros in . |
Constraints
Example:
| Input | Output |
|---|---|
| 20 | 4 |
解法
分析
這題十分經典,是要求尾部有幾個。
注意到尾部的個數滿足的的最大值(也就是能被整除幾次)的質因數分解中的次方數(因為,而又顯然的質因數分解中的次數會比來的少)
接著,的質因數分解中的次數即為~中每個數個別被整除的次數之和。
~中,
- 被整除的數有個
- 被整除的數有個
- 被整除的數有個
等等,於是所求即
此即勒讓德定理(Legendre’s Theorem):
其中表示滿足的最大正整數(即被整除幾次)
在計算時,我們可以用以下性質簡化計算:
AC Code
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int z = n, ans = 0;
while(z != 0){
z /= 5;
ans += z;
}
cout << ans;
}
很簡單吧~
本部落格所有文章除特別聲明外,均採用CC BY-NC-SA 4.0 授權協議。轉載請註明來源 R3X's Blog!



![[Note] Writing a simple Program in C - LiveOverflow](/2026/06/03/Note-Writing-a-simple-Program-in-C-LiveOverflow/output.png)