hdu1042 N! 大数阶乘

N!

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 90086    Accepted Submission(s): 26656


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
 

Author
//int数组只存数的一位太浪费了,不如让它的空间发挥到极限,数组一个元素存一个不超过10^5的数
//这样一个元素就可以存5位,开的数组就可以小5倍,只需要8000就可以。 

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define N 8000
int s[N];
int main()
{
	int n,i,j,k,t;
	while((scanf("%d",&n))!=EOF)
	{
		memset(s,0,sizeof(s));//记得要初始化 
	    s[0]=1;
		for(i=2;i<=n;i++)
		{  
			for(t=0,j=0;j<N;j++)
			{
				k=s[j]*i+t;
				s[j]=k%100000;
				t=k/100000;
/*
为什么k对10^5取余:因为k就算是无符号型最大为 2^32-1,刚刚超过10^9,
而s[j]<10^5,i<10^4,t<10^4,加一块最大值小于2^31-1,假如让s数组一个存6位的话,s[j]<10^6,i<10^4,t<10^4,
就可能超过2^32-1了!所以s数组元素最多存5位!即99999 
*/ 
			}
		} 
		for(i=N-1;!s[i];i--);  //除去前导零 
		printf("%d",s[i]);  //第一个元素不要求输出多个零 
		while(i)
		printf("%05d",s[--i]);//这些需要输出前面多余的零,不然判题错误 
		printf("\n");
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/cao2219600/article/details/80169680