大数阶乘
源代码
#include <cstring> #include <cstdio> int a[20000]; int main() { int m, ans, carray,num;//m为输入数,ans为当前数与乘积数的每一位的乘积,carray为进位数 //比如ans + carray = 5015,那么更新乘积的当前位为5,carray更新为501(右移了一位),num为需要多少位数组 while (scanf("%d",&m)!=EOF) { memset(a,0,20000); a[0] = 1; carray = 0; num = 1; for (int j = 1; j <= m; j++) { for (int i = 0; i < num; i++) { ans = a[i] * j; a[i] = (ans + carray) % 10; carray = (ans + carray) / 10; if (carray && num < i + 2) num = i + 2; } } int i = 20000; while (!a[--i]); for (; i >= 0; i--) { printf("%d",a[i]); } printf("\n"); } return 0; }
最优源代码
#include<stdio.h> #include<string.h> const int maxn=20000; int a[maxn]; int main() { int n,i,j,s,c; scanf("%d",&n); memset(a,0,sizeof(a)); a[0]=1; for(i=2;i<=n;i++) {c=0; for(j=0;j<=maxn;j++) { s=a[j]*i+c; a[j]=s%10; c=s/10; } } for(j=maxn;j>=0;j--) if(a[j]) break; for(i=j;i>=0;i--) printf("%d",a[i]); printf("\n"); return 0; }