Long factorial

 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>
#include <vector>
using namespace std;
int fact(int n) {if(n==0) return 1; else return n*fact(n-1);}
int main() {
freopen("fact.in", "r", stdin);
freopen("fact.out", "w", stdout);
int n, carry=0, tmp=0, F[10000], last=0;
for(int i=0; i<10000; i++) F[i]=0;
scanf("%d", &n);
if(n<13) {printf("%d", fact(n)); return 0;}
F[last++]=n;
for(int i=1; i<n; i++) {
carry=0;
for(int j=0; j<=last; j++) {
tmp=F[j]*i;
F[j]=tmp%10000 + carry;
if(F[j]>=10000) {
carry=tmp/10000 + F[j]/10000;
F[j]%=10000;
}else {
carry=tmp/10000;
}
}
if(carry>0) {
F[++last]=carry;
carry=0;
}
}
printf("%d", F[last]);
for(int i=last-1; i>=0; i--) {
if(F[i]==0) {
printf("0000");
}
else {
if(F[i]<10) {
printf("000%d", F[i]);
}
else {
if(F[i]<100) {
printf("00%d", F[i]);
}
else {
if(F[i]<1000) {
printf("0%d", F[i]);
}
else {
printf("%d", F[i]);
}
}
}
}
}
return 0;
}