When dealing with integers that exceed the range of standard data types (such as long long), we need arbitrary-precision arithmetic, commonly known as "big integer" operations. This approach processes numbers digit by digit using arrays or strings, handling carries manually to support values of virtually any size.
High-Precision Addition
The core idea is to simulate manual addition: align digits from right to left, add corresponding positions, and propagate carries. The result is stored in reverse order and output accordingly.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void bigIntegerAdd(const string& num1, const string& num2) {
vector<int> sum;
int idx1 = num1.size() - 1;
int idx2 = num2.size() - 1;
int carry = 0;
while (idx1 >= 0 || idx2 >= 0 || carry > 0) {
int digitSum = carry;
if (idx1 >= 0) digitSum += num1[idx1--] - '0';
if (idx2 >= 0) digitSum += num2[idx2--] - '0';
sum.push_back(digitSum % 10);
carry = digitSum / 10;
}
for (int k = sum.size() - 1; k >= 0; k--) {
cout << sum[k];
}
}
int main() {
string str1, str2;
cin >> str1 >> str2;
bigIntegerAdd(str1, str2);
return 0;
}
High-Precision Multiplication
Multiplication follows the standard long multiplication algorithm. Each digit of the first number multiplies each digit of the second number, with products added to the appropriate position. Carries are handled after all multiplications. This works for both large number × large number and large number × small numbeer scenarios.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void bigIntegerMultiply(const string& num1, const string& num2) {
int len1 = num1.size();
int len2 = num2.size();
vector<int> product(len1 + len2, 0);
for (int i = len1 - 1; i >= 0; i--) {
for (int j = len2 - 1; j >= 0; j--) {
int mul = (num1[i] - '0') * (num2[j] - '0');
int highPos = i + j;
int lowPos = i + j + 1;
int total = mul + product[lowPos];
product[lowPos] = total % 10;
product[highPos] += total / 10;
}
}
int start = 0;
while (start < product.size() && product[start] == 0) {
start++;
}
if (start == product.size()) {
cout << 0;
return;
}
for (int k = start; k < product.size(); k++) {
cout << product[k];
}
}
int main() {
string str1, str2;
cin >> str1 >> str2;
bigIntegerMultiply(str1, str2);
return 0;
}
Both implementations read numbers as strings too preserve all digits, process them from the least significent digit, and handle edge cases such as leading zeros in the result.