要么改变世界,要么适应世界

阶乘求和

2020-05-22 22:21:00
112
目录

题目来源:C语言网1014

问题描述

求Sn=1!+2!+3!+4!+5!+…+n!之值,其中n是一个数字(n不超过20)。

样例输入

5

样例输出

153

问题求解

/*
 * @Author: YaleXin
 * @Date: 2020-05-22 20:40:31
 * @LastEditTime: 2020-05-22 22:19:56
 * @LastEditors: YaleXin
 * @Description:
 * @FilePath: \my_c_workspace\dotcpp\1014.c
 * @祈祷不出现BUG
 */
#include <stdio.h>
#define MAX_NUM 100
typedef struct factorial {
    int factorial[100];
} f;
f num[25];
int ans[100] = {0};
// 高精度存储
void setNum(int index) {
    if (index == 1) {
        num[1].factorial[1] = 1;
        return;
    } else {
        int c = 0, mul = 0, i;
        for (i = 1;; i++) {
            mul = (num[index - 1].factorial[i] * index + c) % MAX_NUM;
            c = (num[index - 1].factorial[i] * index + c) / MAX_NUM;
            num[index].factorial[i] = mul;
            if ((mul + c + num[index - 1].factorial[i + 1]) == 0) break;
        }
    }
}
int addAns(int index) {
    int c = 0, i, sum = 0;
    for (i = 1;; i++) {
        sum = (ans[i] + num[index].factorial[i] + c) % MAX_NUM;
        c = (ans[i] + num[index].factorial[i] + c) / MAX_NUM;
        ans[i] = sum;
        if ((sum + c + ans[i + 1]) == 0) break;
    }
    return i;
}
int main() {
    int n, i, len;
    scanf("%d", &n);
    for (i = 1; i <= n; i++) {
        setNum(i);
        len = addAns(i);
    }
    for (i = len - 1; i >= 1; i--) {
        // 首位前导零去掉
        if (ans[i] < 10 && i != len - 1) {
            printf("0%d", ans[i]);
        } else {
            // 个位数补零
            printf("%d", ans[i]);
        }
    }
    return 0;
}
历史评论
开始评论