阶乘和 大整数

///大整数阶乘的和
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    while(cin>>n)
    {
        int a[2000]= {1},b[2000]= {0}; //存放结果的数组a。
        int c; //b用于存放每位存放的结果。
        int r=0; //r用来表示进位的数。
        int h=1,hb=1;  //h用来表示运算过程中 结果a 的最高位在哪。
        for (int i=1; i<=n; i++)
        {
            for (int j=0; j<h; j++)
            {
                c= a[j]*i+r; //两数相乘 。
                a[j]=c%10; //求该位的真实数据 。
                r=c/10; //求进位
            }
            while(r) //上面j的循环结束后,r表示最高位有无进位。
            {
                a[h++]=r%10; //如果有,最高位应再进一,并计算最高位上的余数
                r/=10; //计算最高位进一后,是否还需要进位。
            }

            int len=max(hb,h);
            for(int k=0; k<len; k++)
            {
                b[k]=a[k]+b[k];
                if(b[k]>9)
                {
                    b[k]-=10;
                    b[k+1]++;
                }
            }
        }
        for(int g=max(hb,h)-1;g>=0;g--)
            cout<<b[g];
        cout<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/tp25959/p/10274237.html
今日推荐