原題鏈接:HDU’s ACM 1042 N!
分析:這是一個顯然的大數問題,因爲N在[0,10000],分析可知結果位數會在10^4數量級,若逐數位處理太慢,考慮多數位處理,但要注意N的不同範圍取值時,數組每個元素所能容納的最大值。另外,可以考慮存儲已經處理的數據,來提升性能。
AC Code:
#include <stdio.h>
#include <string.h>
#define MAXN 10000 + 2000
int MAX_NUM_PER_NUM = 100000;
int res[MAXN];
int main()
{
int N;
int i, j, len;
while(scanf("%d", &N) == 1){
memset(res, 0, sizeof(int)*MAXN);
i = j = len = 0;
res[0] = 1;
if(N == 10000)
MAX_NUM_PER_NUM = 10000;
else
MAX_NUM_PER_NUM = 100000;
for(i = 1;i<=N;++i){
for(j = 0;j<=len;++j)
res[j] *= i;
for(j = 0;j<=len;++j){
res[j+1] += res[j] / MAX_NUM_PER_NUM;
res[j] %= MAX_NUM_PER_NUM;
}
len = res[len+1]? len+1 : len;
}
printf("%d", res[len--]);
if(N == 10000)
while(len>=0)
printf("%04d", res[len--]);
else
while(len>=0)
printf("%05d", res[len--]);
printf("\n");
}
return 0;
}
WC Code(待糾正):
#include <stdio.h>
#include <string.h>
#define MAXN 10000 + 2000
int MAX_NUM_PER_NUM = 100000;
int res[MAXN];
int main()
{
int N;
int i, j, len;
int tmp;
int digitNum; // 標識數組每個元素可以容納的最大數字的數位,供輸出使用
while(scanf("%d", &N) == 1){
memset(res, 0, sizeof(int)*MAXN);
i = j = len = 0;
res[0] = 1;
tmp = N/10;
digitNum = 9;
MAX_NUM_PER_NUM = 1000000000; // MAX_NUM_PER_NUM = 10^9
while(tmp){
MAX_NUM_PER_NUM /= 10;
tmp /= 10;
digitNum--;
}
for(i = 1;i<=N;++i){
for(j = 0;j<=len;++j)
res[j] *= i;
for(j = 0;j<=len;++j){
res[j+1] += res[j] / MAX_NUM_PER_NUM;
res[j] %= MAX_NUM_PER_NUM;
}
len = res[len+1]? len+1 : len;
}
printf("%d", res[len--]);
while(len>=0)
printf("%0*d", digitNum, res[len--]);
printf("\n");
}
return 0;
}