Files
python/GESP/Mkx/jiecheng,sum.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

74 lines
1.3 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
const int BASE = 10000; // 基数为10000
int a[N], al; // 存储最终的和
int f[N], fl; // 存储当前阶乘值
/*
测试用例:
6
答案873
*/
// 高精度乘以低精度
void mul(int a[], int &al, int b) {
int t = 0;
for (int i = 0; i < al; i++) {
t += a[i] * b;
a[i] = t % BASE;
t /= BASE;
}
if (t)
a[al++] = t;
while (al > 1 && a[al - 1] == 0)
al--;
}
// 高精度加法
void add(int a[], int &al, int b[], int bl) {
int t = 0;
al = max(al, bl);
for (int i = 0; i < al; i++) {
if (i < bl)
t += b[i];
t += a[i];
a[i] = t % BASE;
t /= BASE;
}
if (t)
a[al++] = t;
}
// 输出高精度数
void print(int a[], int al) {
// 8->0008 x 8
printf("%d", a[al - 1]);
for (int i = al - 2; i >= 0; i--) // 789->0789
printf("%04d", a[i]);
printf("\n");
}
int main() {
int n;
cin >> n;
// 初始化阶乘数组和和数组
f[0] = 1;
fl = 1;
a[0] = 0;
al = 1;
// 计算1!到n!并累加
for (int i = 1; i <= n; i++) {
// 计算i!
mul(f, fl, i);
// 将i!加到总和中
add(a, al, f, fl);
}
// 输出结果
print(a, al);
return 0;
}