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
模板,每次计算阶乘数值,并将每位数值存放在数组中,模拟手算的原理,每次从低位开始乘,逐步到高位,期间不停更新数组中的数值。
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 #include <cstring> 5 #include <string.h> 6 using namespace std; 7 const int maxn=40000; 8 int d[maxn]; 9 int main() 10 { 11 int n; 12 while(cin>>n){ 13 memset(d,0,sizeof(d)); 14 d[0]=1; 15 int t=0,tmp=0,carry=0; 16 for(int i=1;i<=n;i++){ 17 for(int j=0;j<=t;j++){ 18 tmp=d[j]*i+carry; 19 d[j]=tmp%10; 20 carry=tmp/10; 21 } 22 while(carry!=0){ 23 d[++t]=carry%10; 24 carry/=10; 25 } 26 } 27 for(int i=t;i>=0;i--){ 28 cout<<d[i]; 29 } 30 cout<<endl; 31 } 32 return 0; 33 }