Here's a C++ implementation that can add two very large numbers (up to 10^64 and beyond) using string-based arithmetic:
cpp
#include <iostream>
#include <string>
#include <algorithm>
std::string addLargeNumbers(std::string num1, std::string num2) {
// Make sure num1 is the longer number
if (num1.length() < num2.length()) {
std::swap(num1, num2);
}
std::string result = "";
int carry = 0;
int i = num1.length() - 1;
int j = num2.length() - 1;
// Add digits from right to left
while (i >= 0 || j >= 0 || carry > 0) {
int sum = carry;
if (i >= 0) {
sum += (num1[i] - '0');
i--;
}
if (j >= 0) {
sum += (num2[j] - '0');
j--;
}
result = char(sum % 10 + '0') + result;
carry = sum / 10;
}
return result;
}
// Function to validate if string contains only digits
bool isValidNumber(const std::string& str) {
if (str.empty()) return false;
for (char c : str) {
if (c < '0' || c > '9') return false;
}
return true;
}
int main() {
std::string num1, num2;
std::cout << "Enter first large number: ";
std::cin >> num1;
std::cout << "Enter second large number: ";
std::cin >> num2;
// Validate input
if (!isValidNumber(num1) || !isValidNumber(num2)) {
std::cout << "Error: Please enter valid positive integers only." << std::endl;
return 1;
}
std::string result = addLargeNumbers(num1, num2);
std::cout << "Sum: " << result << std::endl;
return 0;
}
Here's an example of how it works:
cpp
// Example usage with very large numbers
int main() {
// Numbers close to 10^64
std::string num1 = "9999999999999999999999999999999999999999999999999999999999999999";
std::string num2 = "1111111111111111111111111111111111111111111111111111111111111111";
std::cout << "Number 1: " << num1 << std::endl;
std::cout << "Number 2: " << num2 << std::endl;
std::cout << "Sum: " << addLargeNumbers(num1, num2) << std::endl;
return 0;
}
Alternative using GMP Library:
If you want to use a more robust solution, you can use the GMP (GNU Multiple Precision Arithmetic) library:
cpp
#include <iostream>
#include <gmp.h>
int main() {
mpz_t num1, num2, result;
// Initialize the variables
mpz_init(num1);
mpz_init(num2);
mpz_init(result);
// Set the values (example with very large numbers)
mpz_set_str(num1, "99999999999999999999999999999999999999999999999999999999999999999", 10);
mpz_set_str(num2, "11111111111111111111111111111111111111111111111111111111111111111", 10);
// Perform addition
mpz_add(result, num1, num2);
// Print the result
std::cout << "Sum: ";
mpz_out_str(stdout, 10, result);
std::cout << std::endl;
// Clean up
mpz_clear(num1);
mpz_clear(num2);
mpz_clear(result);
return 0;
}
To compile with GMP:
bash
g++ -o bigint program.cpp -lgmp
The string-based approach is self-contained and doesn't require external libraries, while GMP provides more comprehensive big integer operations and better performance for very large numbers.