高精度除法(非重点)

算法思路(竖式模拟)

代码实现

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

// 比较两个正整数字符串的大小(已去除前导零)
bool greaterOrEqual(const string& a, const string& b) {
    if (a.size() != b.size()) return a.size() > b.size();
    return a >= b;
}

// 高精度减法:a - b,要求 a >= b,返回结果字符串
string subString(const string& a, const string& b) {
    string res;
    int borrow = 0;
    int i = a.size() - 1, j = b.size() - 1;
    while (i >= 0 || j >= 0) {
        int diff = (i >= 0 ? a[i] - '0' : 0) - borrow;
        if (j >= 0) diff -= (b[j] - '0');
        if (diff < 0) {
            diff += 10;
            borrow = 1;
        } else {
            borrow = 0;
        }
        res.push_back(diff + '0');
        i--; j--;
    }
    // 去除前导零
    while (res.size() > 1 && res.back() == '0') res.pop_back();
    reverse(res.begin(), res.end());
    return res;
}

// 高精度乘法:字符串 * 一位整数 (0-9)
string mulString(const string& a, int d) {
    if (d == 0) return "0";
    string res;
    int carry = 0;
    for (int i = a.size() - 1; i >= 0; --i) {
        int prod = (a[i] - '0') * d + carry;
        res.push_back(prod % 10 + '0');
        carry = prod / 10;
    }
    while (carry) {
        res.push_back(carry % 10 + '0');
        carry /= 10;
    }
    reverse(res.begin(), res.end());
    return res;
}

// 高精度除法:a / b,返回商和余数(余数通过引用返回)
string divBig(const string& a, const string& b, string& remainder) {
    if (b == "0") throw runtime_error("Division by zero");
    if (!greaterOrEqual(a, b)) {
        remainder = a;
        return "0";
    }
    string quotient;
    remainder = "";   // 当前余数(初始为空)
    // 遍历被除数的每一位
    for (char ch : a) {
        remainder.push_back(ch);           // 将下一位加入余数末尾
        // 去除余数的前导零(保留一个 '0')
        size_t pos = remainder.find_first_not_of('0');
        if (pos != string::npos) remainder = remainder.substr(pos);
        else remainder = "0";

        // 在当前余数下试商(0-9)
        int q = 0;
        string product;
        // 尝试从9到0,找到最大的 q 使得 q*b <= remainder
        for (int d = 9; d >= 0; --d) {
            product = mulString(b, d);
            if (greaterOrEqual(remainder, product)) {
                q = d;
                break;
            }
        }
        quotient.push_back(q + '0');
        // 减去 product
        remainder = subString(remainder, product);
    }
    // 去除商的前导零
    size_t pos = quotient.find_first_not_of('0');
    if (pos == string::npos) quotient = "0";
    else quotient = quotient.substr(pos);
    // 余数可能为空,则置 "0"
    if (remainder.empty()) remainder = "0";
    return quotient;
}

int main() {
    string a, b;
    cin >> a >> b;
    string rem;
    string q = divBig(a, b, rem);
    cout << "商: " << q << "\n余数: " << rem << endl;
    return 0;
}