1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <string>
#include <algorithm>
// 大数加法
std::string addLargeNumbers(std::string num1, std::string num2) {
int carry = 0;
std::string result = "";
while (num1.length() < num2.length()) num1 = "0" + num1;
while (num2.length() < num1.length()) num2 = "0" + num2;
for (int i = num1.length() - 1; i >= 0; i--) {
int sum = (num1[i] - '0') + (num2[i] - '0') + carry;
carry = sum / 10;
result = std::to_string(sum % 10) + result;
}
if (carry) result = std::to_string(carry) + result;
return result;
}
// 大数减法
std::string subtractLargeNumbers(std::string num1, std::string num2) {
std::string result = "";
bool isNegative = false;
if (num1.length() < num2.length() || (num1.length() == num2.length() && num1 < num2)) {
std::swap(num1, num2);
isNegative = true;
}
while (num2.length() < num1.length()) num2 = "0" + num2;
int borrow = 0;
for (int i = num1.length() - 1; i >= 0; i--) {
int diff = (num1[i] - '0') - (num2[i] - '0') - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
result = std::to_string(diff) + result;
}
result.erase(0, std::min(result.find_first_not_of('0'), result.size()-1));
return isNegative ? "-" + result : result;
}
// 大数乘法
std::string multiplyLargeNumbers(std::string num1, std::string num2) {
if (num1 == "0" || num2 == "0") return "0";
int n = num1.length();
int m = num2.length();
std::string result(n + m, '0');
for (int i = n - 1; i >= 0; i--) {
int carry = 0;
int a = num1[i] - '0';
for (int j = m - 1; j >= 0; j--) {
int b = num2[j] - '0';
int prod = a * b + carry + (result[i + j + 1] - '0');
carry = prod / 10;
result[i + j + 1] = (prod % 10) + '0';
}
result[i] += carry;
}
result.erase(0, std::min(result.find_first_not_of('0'), result.size()-1));
return result;
}
// 大数除法
std::string divideLargeNumbers(std::string dividend, std::string divisor) {
// 略
return "To be implemented";
}
int main() {
std::string num1 = "123456789012345678901234567890";
std::string num2 = "987654321098765432109876543210";
std::string sum = addLargeNumbers(num1, num2);
std::string difference = subtractLargeNumbers(num1, num2);
std::string product = multiplyLargeNumbers(num1, num2);
std::cout << "Sum: " << sum << std::endl;
std::cout << "Difference: " << difference << std::endl;
std::cout << "Product: " << product << std::endl;
return 0;
}