高精度减法,求a-b a,b都不超过240位
#include <bits/stdc++.h>
using namespace std;
const int N = 10090;
int a[N], b[N], c[N];
int flag = 0;
int main()
{
string str1;
string str2;
cin >> str1;
cin >> str2;
if ((atoi(str1.c_str()) < atoi(str2.c_str()) && str1.size() == str2.size()) || str1.size() < str2.size()){
swap(str1, str2);
flag = 1;
}
for (int i = 0; i < str1.size(); i ++)
a[str1.size()-1-i] = str1[i] - '0';
for (int i = 0; i < str2.size(); i ++)
b[str2.size()-i-1] = str2[i] - '0';
int ans = max(str1.size(), str2.size());
for (int i = 0; i < ans; i ++){
if (a[i] < b[i]){
a[i+1] -= 1;
a[i] += 10;
}c[i] = a[i] - b[i];
}
while (c[ans-1] == 0 && ans > 1)
ans -= 1;
if (flag == 1)
cout << "-";
for (int i = 0; i < ans; i ++)
cout << c[ans-1-i];
return 0;
}
这个代码有什么问题吗
1200000=2X2X2X2X2X2X2X3X5X5X5X5X5
2:7次方
3:一次方
5:5次方
所以有正约数:
(7+1)X(1+1)X(5+1)
=8X2X6
=16X6
=96个
问题解答:
高精度减法问题
1.首先,需要用字符串存储a和b,因为它们的位数超过了long long类型的限制,同时字符串还可以通过下标操作来实现高精度计算,方便操作。
2.找到两个字符串之间某一位的差,进行减法操作,注意需要借位(逆序处理可以少处理一步借位)。
3.最后还要将结果的前导0去掉。
以下是代码实现过程:
#include <bits/stdc++.h>
using namespace std;
string minusStrings(string a, string b) { //定义高精度减法函数
string c;
int len1 = a.length(), len2 = b.length(), i, j, k = 0, borrow = 0;
for (i = len1 - 1, j = len2 - 1; i >= 0 && j >= 0; --i, --j) {
int temp = a[i] - b[j] - borrow; //temp存储a,b对应位相减的结果
if (temp < 0) {
temp = 10 + temp;
borrow = 1;
} else {
borrow = 0;
}
c += temp + '0'; //得到对应位的差值,添加到c字符串中
}
while (i >= 0) { //处理余下的a中多余的位
int temp = a[i] - '0' - borrow;
if (temp < 0) {
temp += 10;
borrow = 1;
} else {
borrow = 0;
}
c += temp + '0';
--i;
}
reverse(c.begin(), c.end()); //翻转c字符串,得到正确的结果
while (c.size() > 1 && c[0] == '0') {
c.erase(c.begin()); //去掉首位多余的0
}
return c; //返回结果
}
int main() {
string a, b;
cin >> a >> b;
string result = minusStrings(a, b);
cout << result << endl;
return 0;
}
参考资料:
https://www.cnblogs.com/TF12138/p/10388154.html
https://blog.csdn.net/weixin_41883771/article/details/82988202
https://blog.csdn.net/weixin_42815676/article/details/82131512