阶乘和

GitHub跳转原题关系图返回列表

递推维护当前阶乘并累加,利用 Python 任意精度整数计算阶乘和。

OJ: noi_openjudge

题目 ID: ch0106-15

难度:入门

标签:高精度数学递推python

日期: 2026-07-30 23:01

题意

计算 S=1!+2!++n!S=1!+2!+\cdots+n!,其中 n50n\leqslant50

思路

维护当前 factorial。第 ii 轮乘以 ii 得到 i!i!,再加入 total。Python 的整数会自动扩展,能直接保存阶乘和。

代码

Python代码

python
limit = int(input())
factorial = 1
total = 0

for number in range(1, limit + 1):
    factorial *= number
    total += factorial

print(total)

C++代码

cpp
/* 高精乘单精 */
/* 高精+高精 */
#include <cstdio>

int a[10000000] = {1};
int b[10000000] = {0};
int len_b = 1;
int cnt = 1;
int n;

void _add(){
    int i,j;
    int _max = len_b;
    if( len_b < cnt)
        _max = cnt;
    for (i=0;i<_max;i++){
        b[i+1] += (b[i]+a[i]) / 10;
        b[i] = (b[i]+a[i]) % 10;
    }
    if( b[_max] != 0)
        len_b = _max+1;
    else
        len_b = _max;

}
void p(){
    int i;
    for(i=cnt-1;i>=0;i--)
        printf("%d",a[i]);
    printf("\n");
    for(i=len_b-1;i>=0;i--)
        printf("%d",b[i]);
    printf("\n");
    printf("\n");
}
int main(){
    scanf("%d",&n);
    int i,j,k;
    for(i=1;i<=n;i++){
        for(j=0;j<cnt;j++){
            a[j] *= i;
        }
        int pre =0;
        for(j=0;j<cnt;j++){
            int t = (a[j] + pre) % 10;
            pre = (a[j] + pre) / 10;
            a[j] = t;
        }
        while( pre != 0){
            a[cnt++] = pre %10;
            pre /=10;
        }

        _add();
        //p();
    }
    for(i=len_b-1;i>=0;i--)
        printf("%d",b[i]);
    return 0;
}

复杂度

循环次数为 nn;实际运行时间还受高精度整数位数增长影响,额外空间为结果所需空间。

总结

阶乘和仍然只需保存一个当前阶乘和一个累计和,无需存储所有阶乘。