这道题是一道大数相乘的题目,本来不是太复杂,但是开始自己思路太死板,写了又长又有错的代码,在看完别人代码后才明白怎么做。另外提示一下,数组最好开到40000,否则可能算出的答案有问题。
代码(C++):
#include <iostream>
#define MAX 40000
using namespace std;
int main()
{
int array[MAX+1],n,k,t,j;
while(cin>>n)
{
if(0==n)
{
cout<<1<<endl;
continue;
}
t=n--;
memset(array,0,sizeof(array));
array[0]=MAX; //记录大数的起始位置
while(t>0)
{
array[array[0]--]=t%10;
t/=10;
}
k=0; //用于保存进位的数字
while(n>1)
{
for(j=MAX;j>array[0];j--)
{
t=k+array[j]*n;
array[j]=t%10;
k=t/10;
}
while(k>0)
{
array[array[0]]=k%10;
k/=10;
array[0]--;
}
--n;
}
for(j=array[0]+1;j<=MAX;j++) cout<<array[j];
cout<<endl;
}
system("PAUSE");
return 0;
}
附上原题:
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