N!
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 99923 Accepted Submission(s): 29875
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
大整数的乘法在算法中是比较重要的一项,无论哪种数据类型都无法满足万位数的乃至更大的数存储要求,所以我们要分位数要储存,比如一个规定用多少位数要储存一个大数的某一部分,然后逐步将大数表示出来。代码及注释如下:
#include<iostream>
#include<stdio.h>
#include<iomanip>
using namespace std;
int main(){
int i,j;
int m;
int n; //测试数据
while(scanf("%d",&n)!=EOF){ //输入数据
if(n<0) //处理负数
continue;
int a[10000]={0}; //表示大整数的数组,一个a[]可以表示一个较大的数
m=0;
a[0]=1;
for( i=1;i<=n;i++)
for( j=0;j<=m;j++)
{
a[j]=a[j]*i; //算术主体
if(j>0&&a[j-1]>=10000){ //求余推至下一a[]进行处理
a[j]=a[j]+a[j-1]/10000;
a[j-1]=a[j-1]%10000;
}
if(a[m]>=10000) //如果a[]大于了10000,也就超过了,格式控制的范围,如果不控制就会导致格式控制
m++;
}
cout<<a[m];
for( i=m-1;i>=0;i--)
printf("%04d",a[i]); //与上文的10000相匹配,0-9999
cout<<endl;
}
}