高精度乘高精度

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

#include <bits/stdc++.h>
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值