N!
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 34687 Accepted Submission(s): 9711
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.基本思想:
把运算结果倒着保存在一个大数组f中。
每次循环更新每一位*(当前的操作数i)+进位c.并处理超过当前数字长度的进位c。更新数字长度。
最后,找到不为零的数组位置,开始倒着输出即可。
1 #include<cstdlib> 2 #include<cstdio> 3 #include<string.h> 4 #define MAX 10000 5 int f[MAX]; 6 int main() 7 { 8 int n;//阶乘数 9 while (scanf("%d",&n)!=EOF) 10 { 11 memset(f,0,sizeof(f));//清空运算数组 12 f[0]=1; 13 int i,j,count=1;//数的总位数,进位时+1 14 for (i = 2; i <=n; i++)//<=n的数循环高精度 15 { 16 int c=0;//进位 17 for (j = 0; j < count; j++) 18 { 19 int ans=f[j]*i+c; 20 f[j]=ans%10;//所在位取余数 21 c=ans/10; 22 } 23 while (c)//进位 24 { 25 f[count++]=c%10; 26 c/=10; 27 } 28 } 29 int k=MAX-1; 30 while (!f[k])k--;//找到数组结果不为零的开始. 31 for (i = k; i >=0 ; i--) 32 printf("%d",f[i]); 33 printf("\n"); 34 } 35 return 0; 36 }