7-7 階乘的非零尾數 (20分)

 

 

 

#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
int main(){
    int n, k;
    cin >> n >> k;
    int base = pow(10, k);//對k位數取模
    int ans1 = 1, ans2 = 0, m = n;

    while(m){// 求解 n! 中包含多少個質因子5
        ans2 += m / 5;
        m /= 5;
    }
    int cnt2 = ans2, cnt5 = ans2;
    for(int i = 1; i <= n; i ++){//求階乘
        int x = i;
        while(cnt2 && x % 2 == 0) x >>= 1, cnt2 --;//減少因子2的個數
        while(cnt5 && x % 5 == 0) x /= 5, cnt5 --;//減少因子5的個數
        ans1 = ans1 * x % base;//結果取模
    }
    string str = to_string(ans1);
    for(int i = 0; i < k - str.size(); i ++) cout << "0";
    cout << ans1 << " " << ans2;
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章