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
#include<stdio.h> #include<string.h> #define max 36000 int main() { int a[max],i,j,n,k,p; while(scanf("%d",&n)!=EOF) { memset(a,0,sizeof(a)); a[1]=1; int c; for(i=2;i<=n;i++) { c = 0; for(j=1;j<max;j++) { a[j] = a[j] * i + c; c = a[j] / 10; a[j] = a[j] % 10; } } for(i=max-1;(a[i]==0)&&(i>=0);i--); if(i>=0) { for(;i>=1;i--) printf("%d",a[i]); } printf("\n"); } return 0; }
这题的思路就是2*3*4*5*...n。把所乘得的数存放在数组中,记得进位!!!
再放个我最开始的代码,哎,超时的伤,你不懂!
1 #include<stdio.h> 2 #include<string.h> 3 #define max 36000 4 int main() 5 { 6 int a[max],i,j,n,k,p; 7 while(scanf("%d",&n),n>=0) 8 { 9 10 memset(a,0,sizeof(a)); 11 a[1]=1; 12 for(i=2;i<=n;i++) 13 { 14 for(k=1;k<max;k++) 15 a[k]*=i; 16 for(j=1;j<max;j++) 17 { 18 if(a[j]>=10) 19 { 20 a[j+1]+=a[j]/10; 21 a[j]%=10; 22 } 23 } 24 } 25 for(i=max-1;(a[i]==0)&&(i>=0);i--); 26 if(i>=0) 27 { 28 for(;i>=1;i--) 29 printf("%d",a[i]); 30 } 31 printf("\n"); 32 33 } 34 return 0; 35 }
时间: 2024-10-11 11:51:25