N!

Time Limit : 10000/5000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 65   Accepted Submission(s) : 18

Font: Times New Roman | Verdana | Georgia

Font Size: ← →

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


Author


JGShining(极光炫影)


做这道题时我们应先回顾一下我们中学时是如何计算多位数相乘的,我们首先列个竖式,先用下面的数去乘上面的每一位相加便可。


代码:


#include <iostream>
#define N 35662
using namespace std;
int main()
{
    int n,p,q,k,i,j,l,t;

    while(cin>>n)
    {
        int s[N]={0};
        s[0]=1;
        t=1;
        for(i=2;i<=n;i++)
        {
            q=0;
            for(j=0;j<t;j++)
            {
                p=s[j]*i+q;
                s[j]=p%10;
                q=p/10;
            }
            while(q)  
           {
            s[t++]=q%10;
            q/=10;
           }
        }



        for(k=t-1;k>=0;k--)
        cout<<s[k];
        cout<<endl;
    }
    return 0;
}


另一种方法:不如第一个简便但思路就是中学的那种竖式相乘法


#include <iostream>
#include <cstring>
using namespace std;
int a[100000],b[200000];
int main()
{
    int n,i,p,t,s,l,j;

    while(cin>>n)
    {
       if(n==1||n==0)
       cout<<'1'<<endl;
       else
       {
           memset(b,0,sizeof(b));
           t=1;
           a[0]=1;
           for(i=2;i<=n;i++)
           {
               p=0;
            for(j=0;j<t;j++)
            {
               s=a[j]*i+p;
               p=s/10;
               b[j]=s%10;
               a[j]=b[j];
            }
           while(p)
           {
               b[t]=p%10;
               a[t]=b[t];
               t++;
               p/=10;
           }
           }
           for(l=t-1;l>=0;l--)
           cout<<b[l];
           cout<<endl;
       }


    }

    return 0;
}