相对于其他三个四则运算,大数除法是最繁琐的一种,这里我们只讨论正数
基本思想就是模拟手算,利用竖式来进行运算。并且我们要回归除法最基本的算法,就是减法的累计,在这里我们就利用减法的累计来算出整数商,因此在解决大数除法前,我们先写一个解决大数减法的函数
代码如下:
#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;
}