数组模拟计算大数阶乘

489 词

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>

const int MAXSIZE=10000;
using namespace std;

void factorial(int n) {
int result[MAXSIZE];
result[0] = 1;
int pos = 0;
for (int i = 1; i <= n; ++i) {
int carry = 0;
for (int j = 0; j <= pos; ++j) {
int tmp = result[j] * i + carry;
result[j] = tmp % 10;
carry = tmp / 10;
}
while (carry > 0) {
result[++pos] = carry % 10;
carry /= 10;
}
}
for (int i = pos; i >= 0; --i) std::cout << result[i];
}
int main(){
int n;
cin >> n;
factorial(n);
}