15:阶乘和

传送门:http://noi.openjudge.cn/ch0106/15/

用高精度计算出S=1!+2!+3!+…+n!(n≤50)

其中“!”表示阶乘,例如:5!=5*4*3*2*1。

输入正整数N,输出计算结果S。

输入
一个正整数N。
输出
计算结果S。
样例输入
5
样例输出
153



#include<iostream>
using namespace std;
#define N 100000
int a[N],n,tot=1,lena=1,ans[N];
int main()
{
    cin>>n;
    a[1]=1;ans[1]=1;
    for(int i=2;i<=n;i++)
    {
        for(int j=1;j<=lena;j++)a[j]*=i;
        for(int j=1;j<=lena;j++)
        {
            if(a[j]>9)
            {
                a[j+1]+=a[j]/10;
                a[j]%=10;
                if(j==lena)lena++;
            }
        }
        tot=max(lena,tot);
        for(int j=1;j<=tot;j++)
            ans[j]+=a[j];
        for(int j=1;j<=tot;j++)
            if(ans[j]>9)
            {
                ans[j+1]++;
                ans[j]-=10;
                if(tot==j)tot++;
            }
    }
    // cout<<tot<<endl;
    for(int i=tot;i>=1;i--)cout<<ans[i];
    cout<<endl;
}

猜你喜欢

转载自www.cnblogs.com/jzxnl/p/11105558.html
今日推荐