杭电1042(大数阶乘)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Albert_Bolt/article/details/82533383

N!

Time Limit: 10000/5000 MS (Java/Others)
Memory Limit: 262144/262144 K (Java/Others)

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

思路:

大数阶乘

AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;

int main()
{
    int a[100001],temp,n,m;
    //1234000保存为a[1]=12340,a[0]=0 
    while(cin>>n)
    {
        m=0;//当前的总位数 
        a[0]=1;
        for(int i=1;i<=n;i++)
        {
            temp=0;//进位 
            for(int j=0;j<=m;j++)
            {
                a[j]=a[j]*i+temp;//a[1]=a[1]*2+a[0]的进位 
                temp=a[j]/100000;//判断结果是否超过100000 
                a[j]%=100000;//a[j]的值只能有5位,超过五位要取余 
            }
            if(temp>0)//若a[0]>100000 
            {
                m++;
                a[m]=temp;//将a[0]大于100000的部分加到a[1]中 
            }
        }
        cout<<a[m];
        for(int i=m-1;i>=0;i--)
        {
            //每个数组元素占5位,不够前面补0 
            printf("%05d",a[i]);
        }
        cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Albert_Bolt/article/details/82533383