今天复习了一下求阶乘
题目:编写一个程序,可以输出10000内的阶乘
#include <cstdio> #include <cstdlib> #include <cstring> #define max_w 8002 #define base 100000 int ans[10002][max_w]; int wei[10002]; int calMulti(int n) { int ci = 0; for(int i = 0; i < wei[n-1]; i++) { int tmp = ans[n-1][i] * n + ci; ci = tmp / base; ans[n][i] = tmp % base; } wei[n] = wei[n-1]; if(ci != 0) { ans[n][wei[n]] = ci; wei[n]++; } } int show(int n) { printf("%d",ans[n][wei[n]-1]); for(int i = wei[n]-2; i >= 0; i--) { printf("%05d",ans[n][i]); } puts(""); } int main(int argc, char const *argv[]) { memset(ans, 0, sizeof(ans)); memset(wei, 0, sizeof(wei)); ans[0][0] = 1; ans[1][0] = 1; wei[0] = wei[1] = 1; for(int i = 2; i <= 10000; i++) { calMulti(i); } int n; while(scanf("%d",&n) != EOF) { show(n); printf("%d ",wei[10000]); } return 0; }
因为int的范围大致是9位,所以base的最大值是 1000000000/10000 = 100000,超过这个值就可能发生溢出的现象
10000的阶乘大致有4 * 10000 = 40000位,10000的阶乘不超过40000/5 = 8000位(事实上,有7132位)