N!---hdu-1042

8325 ワード

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("
"); } 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("
"); 32 33 } 34 return 0; 35 }