求助

P1009 [NOIP1998 普及组] 阶乘之和

bjqxszx_zhuzixuan @ 2024-07-08 18:14:57

#include<bits/stdc++.h>
using namespace std;
vector<int> sum,ans;
int n;
inline vector<int> mul(vector<int>&A,int &b)
{
    vector<int>C;
    int t=0;
    for(int i=0,t=0;i<A.size()||t;i++)
    {
        if(i<A.size())
        t+=b*A[i];
        C.push_back(t%10);
        t/=10;
    }
    while(C.size()>1&&C.back()==0)
    C.pop_back();
    return C;
}
inline vector<int> add(vector<int>A,vector<int>B)
{
    vector<int>C;
    int t=0;
    for(int i=0;i<A.size()||i<B.size();i++)
    {
        if(i<A.size())
        t+=A[i];
        if(i<B.size())
        t+=B[i];
        C.push_back(t%10);
        t/=10;
    }
    if(t)
    C.push_back(t);
    return C;
}
int main()
{
    cin>>n;
    for(int i=2;i<=n;i++)
    {
        sum=mul(sum,i);
        ans=add(sum,ans);
    }
    for(int i=ans.size()-1;i>=0;i++)
    cout<<ans[i];
    return 0;
}

by wangjingxi_ @ 2024-07-08 18:46:41

@bjqxszx_zhuzixuan


#include <bits/stdc++.h>
using namespace std;

vector<int> mul(vector<int>& A, int b) {
    vector<int> C;
    int t = 0;
    for (int i = 0; i < A.size() || t; i++) {
        if (i < A.size())
            t += b * A[i];
        C.push_back(t % 10);
        t /= 10;
    }
    while (C.size() > 1 && C.back() == 0)
        C.pop_back();
    return C;
}

vector<int> add(vector<int> A, vector<int> B) {
    vector<int> C;
    int t = 0;
    for (int i = 0; i < A.size() || i < B.size(); i++) {
        if (i < A.size())
            t += A[i];
        if (i < B.size())
            t += B[i];
        C.push_back(t % 10);
        t /= 10;
    }
    if (t)
        C.push_back(t);
    return C;
}

int main() {
    int n;
    cin >> n;

    vector<int> sum(1, 1);
    vector<int> ans(1, 0);

    for (int i = 1; i <= n; i++) {
        sum = mul(sum, i);
        ans = add(ans, sum);
    }

    for (int i = ans.size() - 1; i >= 0; i--)
        cout << ans[i];
    return 0;
}
AC,求关

by bjqxszx_zhuzixuan @ 2024-07-08 18:48:36

谢谢 已关


|