用c++写一个高精度除法代码
时间: 2023-12-31 12:21:10 浏览: 112
以下是一个简单的高精度除法的C++代码示例:
```c++
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int MAXN = 10010; // 数组的最大长度
const int BASE = 10; // 进制
struct BigInt {
int len, s[MAXN];
BigInt() {
memset(s, 0, sizeof(s));
len = 1;
}
BigInt(int num) {
*this = num;
}
BigInt(const char* num) {
*this = num;
}
BigInt operator = (int num) {
char s[MAXN];
sprintf(s, "%d", num);
*this = s;
return *this;
}
BigInt operator = (const char* num) {
memset(s, 0, sizeof(s));
len = strlen(num);
for (int i = 0; i < len; i++) s[i] = num[len - 1 - i] - '0';
return *this;
}
string str() const {
string res = "";
for (int i = 0; i < len; i++) res = (char)(s[i] + '0') + res;
if (res == "") res = "0";
return res;
}
BigInt operator + (const BigInt& b) const {
BigInt c;
c.len = 0;
for (int i = 0, g = 0; g || i < max(len, b.len); i++) {
int x = g;
if (i < len) x += s[i];
if (i < b.len) x += b.s[i];
c.s[c.len++] = x % BASE;
g = x / BASE;
}
return c;
}
BigInt operator - (const BigInt& b) const {
BigInt c;
c.len = 0;
for (int i = 0, g = 0; i < len; i++) {
int x = s[i] - g;
if (i < b.len) x -= b.s[i];
if (x >= 0) g = 0;
else {
g = 1;
x += BASE;
}
c.s[c.len++] = x;
}
c.trim();
return c;
}
BigInt operator * (const BigInt& b) const {
BigInt c;
c.len = len + b.len;
for (int i = 0; i < len; i++)
for (int j = 0; j < b.len; j++)
c.s[i + j] += s[i] * b.s[j];
for (int i = 0; i < c.len - 1; i++) {
c.s[i + 1] += c.s[i] / BASE;
c.s[i] %= BASE;
}
c.trim();
return c;
}
// 高精度除法
BigInt operator / (const BigInt& b) const {
BigInt c;
c.len = len - b.len + 1;
for (int i = c.len - 1; i >= 0; i--) {
BigInt t = b;
if (*this < t * BigInt(BASE) * BigInt(i)) {
c.s[i] = 0;
continue;
}
int l = 0, r = BASE - 1, ans;
while (l <= r) {
int mid = (l + r) >> 1;
if (*this >= t * BigInt(mid)) {
ans = mid;
l = mid + 1;
} else r = mid - 1;
}
c.s[i] = ans;
*this = *this - t * BigInt(ans);
}
c.trim();
return c;
}
// 去掉前导0
void trim() {
while (len > 1 && !s[len - 1]) len--;
}
// 判断大小
bool operator < (const BigInt& b) const {
if (len != b.len) return len < b.len;
for (int i = len - 1; i >= 0; i--)
if (s[i] != b.s[i]) return s[i] < b.s[i];
return false;
}
bool operator > (const BigInt& b) const {
return b < *this;
}
bool operator <= (const BigInt& b) const {
return !(b < *this);
}
bool operator >= (const BigInt& b) const {
return !(*this < b);
}
bool operator != (const BigInt& b) const {
return b < *this || *this < b;
}
bool operator == (const BigInt& b) const {
return !(b < *this) && !(*this < b);
}
};
ostream& operator << (ostream& out, const BigInt& x) {
out << x.str();
return out;
}
istream& operator >> (istream& in, BigInt& x) {
string s;
in >> s;
x = s.c_str();
return in;
}
int main() {
BigInt a, b, c;
cin >> a >> b;
c = a / b;
cout << c << endl;
return 0;
}
```
该代码中定义了一个结构体`BigInt`,表示高精度整数。实现了加法、减法、乘法和除法操作。其中,高精度除法的实现是用二分法来找出商的每一位。
使用时只需要输入两个字符串,分别表示被除数和除数,然后调用`/`操作符即可得到商。
阅读全文