N!
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Problem Description
Given an integer N(0 ≤ N ≤ 10000), your task is to calculate N!
Input
One N in one line, process to the end of file.
Output
For each N, output N! in one line.
Sample Input
1
2
3
Sample Output
1
2
6
題目分析:用數組模擬乘法。讓a[0]保存結果的各位,a[1]是十位,a[2]是百位……(為什麼要逆序表示呢?因為如果按照從高到低的順序儲存,一旦進位的話就……),則每次只需要模擬手算即可完成n!。在輸出時需要忽略前導0.注意,如果結果本身就是0,那麼忽略前導0後將什麼都不輸出。所幸n!肯定不等於0,因此本題可以忽略這個細節。
#include<stdio.h>
#include<string.h>
const int maxn=40000; /*數組不能太小,小了存不下*/
int a[maxn];
int main()
{
int i,j,n;
while(~scanf("%d",&n))
{
memset(a,0,sizeof(a));
a[0]=1;
for(i=2;i<=n;i++)
{
int c=0; /*保存進位*/
for(j=0;j<maxn;j++)
{
int s=a[j]*i+c;
a[j]=s%10;
c=s/10;
}
}
for(j=maxn-1;j>=0;j--) /*去掉前導零*/
if(a[j])
break;
for(i=j;i>=0;i--)
printf("%d",a[i]);
printf("\n");
}
return 0;
}