文章

119

粉丝

68

获赞

92

访问

20.2k

头像
阶乘问题 题解:效率极高的解法
P1059
发布于2025年2月10日 15:34
阅读数 113

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    while (cin >> n) {
        int ans = 1;
        int count2 = 0, count5 = 0; // 统计因子 2 和 5 的数量
        for (int i = 1; i <= n; i++) {
            int x = i;
            while (x % 2 == 0) { x /= 2; count2++; } // 去除因子 2
            while (x % 5 == 0) { x /= 5; count5++; } // 去除因子 5
            ans = (ans * x) % 10; // 只保留最后一位
        }
        // 补回多余的因子 2
        for (int i = 0; i < count2 - count5; i++) {
            ans = (ans * 2) % 10;
        }
        cout << ans << endl;
    }
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发