The factorial of n (to 10000) does not exceed the time limit!

N!

‎Given an integer N (0 ≤ N ≤ 10000), your task is to calculate N!

‎Enter‎

‎A line of N is processed to the end of the file.

Export

‎For every N, output N! In one line.

Sample Input

1
2
3

Sample Output

1
2
6

Idea: usually solve the problem of large number arithmetic data out of range using arrays to simulate

For the factorial of large numbers, the most important thing is how to store each digit of each number and the corresponding array element

Implementation code:

#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
	int i,j,n,l,num,t;
	while(~scanf("%d",&n))
	{
		int s[8000]={1};
		l=1;/*l用来记录该数的长度*/
		for(i=2;i<=n;i++)
		{
			num=0;
			for(j=0;j<l;j++)
			{
				t=s[j]*i+num;
				num=t/100000;
				s[j]=t%100000;/*为了防止时间超限*/
			}
			while(num!=0)
			{
				s[l++]=num%100000;/*如果进位,数组运算实际长度加一*/
				num=num/100000;
			}
		}
		/*这里的输出注意*/
		j=l-1;
		printf("%d",s[j--]);
		for(;j>=0;j--)
		{
			printf("%05d",s[j]);
		}
		printf("\n");
	}
	return 0;
}

The following code is similar but with Runtime Error as a comparison:

#include<stdio.h>
#include<string.h>
int main()
{
	int n;
	while(scanf("%d",&n),n>=0)
	{
		int a[20010];/*储存每一位所得到的的数*/
		int i,j;
		int temp,dight=1;/*temp储存每次得到的数,dight每次得到的数的位数*/
		a[0]=1;
		 
		for(i=2;i<=n;i++)
		{ 
			int num=0;/*储存进位数*/ 
			for(j=0;j<dight;j++)/*每一位的数都分别乘以i*/
			{
				temp=a[j]*i+num;/*temp储存每次得到的数*/
				a[j]=temp%10;
				num=temp/10;
			}
			while(num)
			{
				a[dight]=num%10;
				num=num/10;
				dight++;
			}
		}
		for(i=dight-1;i>=0;i--)
		{
			printf("%d",a[i]);
		}
		printf("\n");
	}
	return 0;
}

AC code reference: https://blog.csdn.net/hnuzengchao/article/details/7287599

Guess you like

Origin blog.csdn.net/with_wine/article/details/113933441