【ACM】hdu_1042_N!_201308071639

N!
Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 43937    Accepted Submission(s): 12362


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_LEN 40000
int s[MAX_LEN];

int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        int i,j,t,sum;
        memset(s,0,sizeof(s));
        s[0]=1;
        for(i=2;i<=n;i++)
        {
            t=0;;
            for(j=0;j<MAX_LEN;j++)
            {
                sum=s[j]*i+t;
                s[j]=sum%10;
                t=sum/10;
            }
        }
        for(i=MAX_LEN-1;(i>0)&&(s[i]==0);i--);
        for(;i>=0;i--)
        printf("%d",s[i]);
        printf("\n");
    }
    return 0;   
}

//此解法耗时3500MS


#include <stdio.h>
#include <string.h>
#define MAX_LEN 40000
int a[MAX_LEN];
int main()
{
    int m;
    while(scanf("%d",&m)!=EOF)
    {
        int i,j,len=0,tem,jin;
        memset(a,0,sizeof(a));
        a[0]=1;
        for(i=2;i<=m;i++)
        {
            jin=0;
            for(j=0;j<=len;j++)
            {
                tem=a[j]*i+jin;
                a[j]=tem%10;
                jin=tem/10;
                if(j==len&&jin!=0)  //如果需要进一位,len+1,这样可以减少循环次数
                len++;
                }
            }
            for(i=len;i>=0;i--)
            printf("%d",a[i]);
            printf("\n");
        }
        return 0;
}

//此解法耗时1218MS

//此解法节省时间

posted @ 2013-08-07 17:51  龙腾四海365  阅读(133)  评论(0编辑  收藏  举报