用c++高精度计算1! 2! ....n! c
时间: 2023-12-11 22:32:18 浏览: 33
以下是用C++高精度计算1! 2! ....n!的代码实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 10000; // 阶乘最大位数
const int MAXM = 100; // 阶乘最大值
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 % 10;
g = x / 10;
}
return c;
}
BigInt operator * (const BigInt& b) const {
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] / 10;
c.s[i] %= 10;
}
while (c.len > 1 && c.s[c.len - 1] == 0) c.len--;
return c;
}
void print() {
for (int i = len - 1; i >= 0; i--) printf("%d", s[i]);
}
};
BigInt fac[MAXM];
void init() {
fac[0] = 1;
for (int i = 1; i < MAXM; i++) fac[i] = fac[i - 1] * i;
}
int main() {
init();
int n;
cin >> n;
fac[n].print();
return 0;
}
```