高精度乘高精度

思路:用vector表示大整数,整数的低位存在数组索引的低位;
A x B = C 其中C的每一位(如第3位),是由AB的相应位相乘累加,处理后得到(如:1+2, 2+1)。

#include 
using namespace std;

const int DEMICAL = 10;

void input(string s, vector<int> &bigNumber)
{
    while (!s.empty()) {
        bigNumber.push_back(s.back() - '0');
        s.pop_back();
    }

}

vector<int> mutiply(vector<int>& a, vector<int>& b)
{
    vector<int> c;
    unsigned cIdx = 0;
    int t = 0;
    for (cIdx = 0; cIdx < a.size() + b.size(); cIdx++) {
        for (unsigned aIdx = 0; aIdx < a.size() && aIdx <= cIdx; aIdx++) {
            unsigned bIdx = cIdx - aIdx;
            if (bIdx < b.size()) {
                t += a[aIdx] * b[bIdx];
            }
        }
        c.push_back(t % DEMICAL);
        t /= DEMICAL;
    }
    while (t) {
        c.push_back(t % DEMICAL);
        t /= DEMICAL;
    }
    while (c.size() > 1 && c.back() == 0) {
        c.pop_back();
    }
    return c;
}

int main(void)
{
    FILE *stream;
    freopen_s(&stream, "./case1.input.txt", "r", stdin);
    string tmpA, tmpB;
    vector<int> numberA;
    vector<int> numberB;
    while (cin >> tmpA >> tmpB) {
        input(tmpA, numberA);
        input(tmpB, numberB);
        vector<int> res = mutiply(numberA, numberB);
        for_each(res.rbegin(), res.rend(), [](int a) { cout << to_string(a); });
        cout << endl;
        numberA.clear();
        numberB.clear();
    }
    return 0;
}

输入示例:case1.input.txt

1 2
3 11
14512451451245124512 15125125124512451245

输出示例:case1.output.txt

2
33
219502644063494817653152060344354417440

你可能感兴趣的:(高精度乘高精度)