Trailing Zeros

一個很經典的高中數學階層問題


N! 乘積結尾有幾個0?


可觀看此影片看數學說明

簡單來說,就是要乘積結尾是0的,在質因數分解中,
一定要一個5跟他前面的一個2

所以
6! 乘積結尾幾個0?
ANS: 1個,因為只有一個5能跟前面任意2做乘積

那 15! 呢,因為5,10,15都能貢獻一個5出來,所以乘積會有3個0

當 20! 時,結尾最多就是4個0,因為5,10,15,20都能貢獻一個5出來

那 $25!$ 的時候呢

因為 $25 = 5*5$ ,他能貢獻兩個5出來,所以25!就會有6個0在結尾

結論

結尾0的個數是根據: N能提供多少個5出來
Q: $30!$ 有幾個0?
ANS: $30/5=6$ ,$6/5=1$ , $6+1 = 7$ 個0

寫法

#include <bits/stdc++.h>
#define io ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
int i;

int main(){ io;
    int n, cnt = 0, iter=5,k;
    cin >> n;

    while(true){
        k = n/iter;
        if ( k!=0){
            cnt+=k;

            iter*=5;
        }
        else{
            break;
        }
    }
    cout << cnt;
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *