问题:用高精度计算出 S = 1! + 2! + 3! + \cdots + n!S=1!+2!+3!+⋯+n!(n \le 50n≤50)。 其中 ! 表示阶乘,定义为 n!=n\times (n-1)\times (n-2)\times \cdots \times 1n!=n×(n−1)×(n−2)×⋯×1。例如,5! = 5 \times 4 \times 3 \times 2 \times 1=1205!=5×4×3×2×1=120。
下面是chatgpt的答案:
以下是使用 C++ 语言实现高精度计算求解S的代码:
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 10000; // 最大位数
const int BASE = 10; // 进制
struct BigInt {
int len, s[MAXN];
BigInt() {
memset(s, 0, sizeof(s));
len = 1;
}
BigInt(int num) {
*this = num;
}
BigInt(const char* num) {
*this = num;
}
BigInt operator = (int num) {
char s[MAXN];
sprintf(s, "%d", num);
*this = s;
return *this;
}
BigInt operator = (const char* num) {
memset(s, 0, sizeof(s));
len = strlen(num);
for (int i = 0; i < len; i++) {
s[i] = num[len - i - 1] - '0';
}
return *this;
}
BigInt operator + (const BigInt& b) const{
BigInt c;
c.len = 0;
for (int i = 0, g = 0; g || i < max(len, b.len); i++) {
int x = g;
if (i < len) x += s[i];
if (i < b.len) x += b.s[i];
c.s[c.len++] = x % BASE;
g = x / BASE;
}
return c;
}
void clean() {
while (len > 1 && !s[len-1]) len--;
}
BigInt operator * (const BigInt& b) {
BigInt c; c.len = len + b.len;
for (int i = 0; i < len; i++)
for (int j = 0; j < b.len; j++)
c.s[i+j] += s[i] * b.s[j];
for (int i = 0; i < c.len-1; i++)
c.s[i+1] += c.s[i]/BASE, c.s[i] %= BASE;
c.clean();
return c;
}
BigInt operator - (const BigInt& b) {
BigInt c; c.len = 0;
for (int i = 0, g = 0; i < len; i++) {
int x = s[i] - g;
if (i < b.len) x -= b.s[i];
if (x >= 0) g = 0;
else {
g = 1;
x += BASE;
}
c.s[c.len++] = x;
}
c.clean();
return c;
}
bool operator < (const BigInt& b) const{
if (len != b.len) return len < b.len;
for (int i = len-1; i >= 0; i--)
if (s[i] != b.s[i])
return s[i] < b.s[i];
return false;
}
bool operator > (const BigInt& b) const{return b < *this;}
bool operator <= (const BigInt& b) {return !(b < *this);}
bool operator >= (const BigInt& b) {return !(*this < b);}
bool operator != (const BigInt& b) {return b < *this || *this < b;}
bool operator == (const BigInt& b) {return !(b < *this) && !(b > *this);}
void print() {
for (int i = len-1; i >= 0; i--) printf("%d",s[i]);
}
};
BigInt fac[55];
int main() {
int n;
cin >> n;
fac[0] = fac[1] = 1;
for (int i = 2; i <= n; i++) {
fac[i] = fac[i-1] * i;
}
BigInt ans;
for (int i = 1; i <= n; i++) {
ans = ans + fac[i];
}
ans.print();
cout << endl;
return 0;
}
其中,BigInt结构体表示高精度整数,支持加、减、乘等运算。在主函数中,我们先预处理出1!到n!的值,然后依次累加即可得到答案。最后输出结果即可。