1 条题解

  • 0
    @ 2026-1-12 14:33:22
    #include <bits/stdc++.h>
    using namespace std;
    
    // a[] :保存“当前阶乘”的高精度结果
    //      低位在前:a[0] 是个位
    // sum[]:保存“阶乘和”的高精度结果
    //      同样是低位在前
    int a[1000], sum[1000];
    
    int main() {
        int n;
        cin >> n;              // 输入 n (n < 50)
    
        int lena = 1;          // lena:当前阶乘 a[] 的有效长度
        int lens = 1;          // lens:阶乘和 sum[] 的有效长度
    
        a[0] = 1;              // 初始化 1! = 1
        sum[0] = 0;            // 阶乘和初始为 0
    
        // 从 1! 一直算到 n!
        for (int i = 1; i <= n; i++) {
    
            /* =========================
               一、计算当前阶乘:a = a * i
               ========================= */
    
            int carry = 0;     // carry:进位
    
            // 对 a[] 的每一位做“乘 i + 进位”
            for (int j = 0; j < lena; j++) {
                int t = a[j] * i + carry; // 当前位乘 i 再加进位
                a[j] = t % 10;            // 当前位保留个位
                carry = t / 10;           // 其余作为进位
            }
    
            // 如果最高位仍有进位,继续扩展长度
            while (carry) {
                a[lena++] = carry % 10;
                carry /= 10;
            }
    
            /* =========================
               二、把当前阶乘加到总和中:sum += a
               ========================= */
    
            carry = 0;
            int maxlen = max(lena, lens); // 两个高精度数的最大长度
    
            for (int j = 0; j < maxlen; j++) {
                // j < lena 时才能取 a[j],否则当作 0
                int t = sum[j] + (j < lena ? a[j] : 0) + carry;
                sum[j] = t % 10;          // 当前位
                carry = t / 10;           // 进位
            }
    
            lens = maxlen;
    
            // 处理加法后可能产生的新进位
            while (carry) {
                sum[lens++] = carry % 10;
                carry /= 10;
            }
        }
    
        /* =========================
           三、输出高精度结果
           ========================= */
    
        // 因为是“低位在前”,所以要逆序输出
        for (int i = lens - 1; i >= 0; i--) {
            cout << sum[i];
        }
        cout << endl;
    
        return 0;
    }
    
    • 1

    信息

    ID
    370
    提交时间
    1000ms
    内存
    256MiB
    难度
    2
    标签
    递交数
    38
    已通过
    8
    上传者