P1134 高精度阶乘
滚动数组。
#include <bits/stdc++.h>
using namespace std;
int main ()
{
int n;
while (cin>>n) {
int a[10000]={0},b[10000]={0},c[10000]={0};
b[0]=1;
int lc=1;
for(int k=1;k<=n;k++){
int p=k,cnt=0;
while (p) {
a[cnt++]=p%10;
p/=10;
}
if(k&1){
for (int i=0;i<10000;i++) c[i]=0;
for (int i=0;i<cnt;i++){
for (int j=0;j<lc;j++){
c[i+j]+=a[i]*b[j];
c[i+j+1]+=c[i+j]/10;
c[i+j]%=10;
}
}
lc+=cnt;
while (!c[lc-1]&&lc>1) lc--;
}
else {
for (int i=0;i<10000;i++) b[i]=0;
for (int i=0;i<cnt;i++){
for (int j=0;j<lc;j++){
b[i+j]+=a[i]*c[j];
b[i+j+1]+=b[i+j]/10;
b[i+j]%=10;
}
}
lc+=cnt;
while (!b[lc-1]&&lc>1) lc--;
}
}
if(n&1){
for (int i=lc-1;i>=0;i--)
printf("%d",c[i]);
std::cout << '\n';
}
else {
for (int i=lc-1;i>=0;i--)
printf("%d",b[i]);
std::cout << '\n';
}
}
return 0;
}