c++,vector求助

P1045 [NOIP2003 普及组] 麦森数

RealDream @ 2024-07-11 21:57:42

求助,有大佬用vector解决吗?

#include <bits/stdc++.h>

using namespace std;

vector<int> mult(vector<int> a, vector<int> b) {
    vector<int> ans;
    ans.reserve(10001);

    int i = 0;
    int val, x = 0;
    for (i = 0; i < (int)a.size(); i++) {
        x = 0;
        for (int j = 0; j < (int)b.size(); j++) {
            val = a[i] * b[j] + x;
            if ((int)ans.size() <= i + j) {
                ans.push_back(val % 10);
            } else {
                val += ans[i + j];
                ans[i + j] = val % 10;
            }

            x = val / 10;
        }
        if (x) ans.push_back(x);

    }
    return ans;
}

void Printf_value(vector<int>& a) {
    vector<int>::reverse_iterator iter = a.rbegin();

    for (; iter != a.rend(); iter++) {
        cout << *iter;
    }
    cout << endl;
}

void Printf_500(vector<int>& a) {
    int index = 0;
    for (int i = a.size(); i < 500; i++) {
        cout << "0";
        index = (index + 1) % 50;
        if (index == 0) cout << endl;
    }

    vector<int>::reverse_iterator iter = a.rbegin();

    for (; iter != a.rend(); iter++) {
        cout << *iter;

        index = (index + 1) % 50;
        if (index == 0) cout << endl;
    }

}

int main() {
    ios::sync_with_stdio(false);
    vector<int> a, ans;
    int n;
    cin >> n;
    a.push_back(2);
    ans.push_back(1);
    while (n != 0) {
        if (n & 1) ans = mult(ans, a);
        a = mult(a, a);
        n /= 2;
    }

    cout << ans.size() << endl;
    ans[0]--;
    Printf_500(ans);

    return 0;
}

|