用vector算高精加和乘,哪里错了?

P1009 [NOIP1998 普及组] 阶乘之和

hope_echo @ 2024-03-28 08:59:54

#include <iostream>
#include <vector>
using namespace std;
vector<int> mul(vector<int> &A, vector<int> &B)
{
    vector<int> c(A.size()+ B.size()+ 10, 0);
    for(int i = 0; i < A.size(); i++)
        for(int j = 0; j < B.size(); j++)
            c[i + j] += A[i] * B[j];

    for(int i = 0; i < c.size(); i++)
    {
        c[i + 1] += c[i] / 10;
        c[i] %= 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(1);
    return c;

}
int main()
{   
    int n;
    cin >> n;
    vector<int> a, c,b,res,ans;
    a.push_back(1);
    ans.push_back(0);
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= i; j++)
        {   

            while(j > 0)
            {
                b.push_back(j % 10);

                j = j / 10;

            }

            c = mul(a,b);
            a = c;
        }
        res = add(ans,a);
        ans = res;
    }
    for(int i = res.size()-1; i >= 0; i--) cout << res[i];

}

by vzcx_host @ 2024-03-28 09:38:35

除了一个可能会导致 RE 的小问题外,高精度加和乘是对的

但是您是不是对循环结构有什么误解,主函数里写的什么?


|