N!
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 262144/262144 K (Java/Others)
Total Submission(s): 65262 Accepted Submission(s): 18665
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
这题我写的时候大部分都会超时,最后网上看了好多,才优化到2000多ms!
在写这篇博客的时候,我问了下学长,他说他900多,当时我就崩溃了,原来他是用G++提交的!
看下代码吧!
没有优化的:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[36000];
int main()
{
int n,i,j,c;
while(scanf("%d",&n)!=EOF)
{
memset(a,0,sizeof(a));
a[0]=1;
for(i=2;i<=n;i++)
{
c=0;
for(j=0;j<36000;j++)
{
a[j]=a[j]*i+c;
c=a[j]/10;
a[j]%=10;
}
}
for(i=36000-1;a[i]==0&&i>=0;i--);
if(i>=0)
for(j=i;j>=0;j--)
printf("%d",a[j]);
printf("\n");
}
return 0;
}
优化后:
#include<stdio.h>
#include<string.h>
int a[36000];
int main()
{
int n,i,j,c,temp,cot;
while(scanf("%d",&n)!=EOF)
{
//memset(a,0,sizeof(a));
a[0]=1;
cot=1;
for(i=2;i<=n;i++)
{
c=0;
for(j=0;j<cot;j++)
{
temp=a[j]*i+c;
c=temp/10;
a[j]=temp%10;
}
while(c)
{
a[cot++]=c%10;
c/=10;//cot用来记录进位
}
}
for(j=cot-1;j>=0;j--)
printf("%d",a[j]);
printf("\n");
}
return 0;
}
后来学长又给了一种方法,300ms左右,谢谢康神教导!
就是数组的一个存5位!
上代码:
#include<stdio.h>
#include<string.h>
long long a[36000];
int main()
{
int n,i,j,c,cot;
int temp;
while(scanf("%d",&n)!=EOF)
{
a[0]=1;
cot=1;
for(i=2;i<=n;i++)
{
c=0;
for(j=0;j<cot;j++)
{
a[j]=a[j]*i+c;
c=a[j]/100000;//每次存5位
a[j]=a[j]%100000;
}
if(c>0)
{
a[cot]=c;
cot++;
}
}
printf("%lld",a[cot-1]);
for(j=cot-2;j>=0;j--)
printf("%05lld",a[j]);
printf("\n");//因为最后面的也就是最高位不需要补0,而其他位不够5位的一定要补够才行,底下这种输出,都没补0,所以会wa
// for(j=cot-1;j>=0;j--)
// printf("%lld",a[j]);
// printf("\n");
}
return 0;
}