大数的除法

 相对于其他三个四则运算,大数除法是最繁琐的一种,这里我们只讨论正数

基本思想就是模拟手算,利用竖式来进行运算。并且我们要回归除法最基本的算法,就是减法的累计,在这里我们就利用减法的累计来算出整数商,因此在解决大数除法前,我们先写一个解决大数减法的函数

代码如下:

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

bool isGreaterOrEqual(string a, string b) {
    if (a.length() != b.length()) {
        return a.length() > b.length();
    }
    return a >= b;
}

string subtract(string a, string b) {
    string result = "";
    int borrow = 0;
    int length = max(a.length(), b.length());
    a = string(length - a.length(), '0') + a;
    b = string(length - b.length(), '0') + b;

    for (int i = length - 1; i >= 0; --i) {
        int digit = (a[i] - '0') - borrow;
        digit -= (b[i] - '0');
        if (digit < 0) {
            digit += 10;
            borrow = 1;
        } else {
            borrow = 0;
        }
        result = char(digit + '0') + result;
    }
    while (result.length() > 1 && result[0] == '0') {
        result.erase(0, 1);
    }
    
    return result;
}

string divideBigNumber(string dividend, string divisor) {
    string result = "";
    string temp = "";

    int idx = 0;
    while (idx < dividend.length()) {
        temp += dividend[idx];
        int count = 0;
        while (isGreaterOrEqual(temp, divisor)) {
            temp = subtract(temp, divisor);
            count++;
        }
        result += char(count + '0');
        idx++;
        if (temp == "0" && idx < dividend.length()) {
            temp = dividend[idx]; 
        }
    }
    if (result == "") {
        result = "0";
    }
    while(result[0]=='0'){
    	result=result.substr(1);
	}
    return result;
}

int main() {
    string num1, num2;
    cin >> num1 >> num2;
    string result = divideBigNumber(num1, num2);
    cout << result << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值