【ACM】大数阶乘 - Java BigInteger实现

大数阶乘

时间限制: 3000 ms  |  内存限制:65535 KB
难度: 3
 
描述
我们都知道如何计算一个数的阶乘,可是,如果这个数很大呢,我们该如何去计算它并输出它?
 
输入
输入一个整数m(0<m<=5000)
输出
输出m的阶乘,并在输出结束之后输入一个换行符
样例输入
50
样例输出
30414093201713378043612608166064768844377641568960512000000000000

思路:模拟正常的乘法运算进行处理,注意进位

 
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstdio>

using namespace std;

int main(){

    int n;
    cin>>n;
    if (n==1||n==0)
    {
        cout<<"1"<<endl;
    }else{

        int a[100000] = {0};
        int i,j,k,sum,t;
        a[0] = 1;
        k = 1;
        for (i = 2; i <= n ; i++)
        {
            sum = 0;
            for (j = 0; j < k ; j++)
            {
                t = a[j]*i + sum;
                a[j] = t % 10;
                sum = t/10;
            }
            while(sum){
                a[k++] = sum%10;
                sum /= 10;
            }
        }
        for (int z = k-1; z>=0 ; z--)
        {
            cout<<a[z];
        }
        cout<<endl;

    }



    return 0;
}        

猜你喜欢

转载自www.cnblogs.com/lyc94620/p/9289253.html
今日推荐