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;
}

 

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