Methods to Handle Large Numbers in C++
One of the most prominent method that is used to handle large numbers is the use of array and strings to store the digits of the number. Using this, we can technically store the number large enough to ever need more size. Many languages such as python already use this technique to represent numbers in contrast to the traditional 32-bit, 64-bit numbers. We can also modify the arithmetic operators to work on these kind of numbers. These type of numbers are also called arbitrary precision numbers.
C++ Program to Handle Large Numbers
To handle very large numbers in C++ we can accept the number from the user in the form of std::string and then we can store each digit of the string in an dynamically allocated interger array. Following is the code for this approach:
// C++ program To handle large numbers using string and
// arrays
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
// Class to handle large numbers
class LargeNumber {
private:
// The large number represented as a string
string number;
public:
LargeNumber(): number("0"){}
LargeNumber(const string& num): number(num){}
// Overloaded operator+ to add two LargeNumber objects
LargeNumber operator+(const LargeNumber& other) const
{
string result;
int carry = 0;
int maxLength
= max(number.length(), other.number.length());
for (int i = 0; i < maxLength || carry; ++i) {
int digit1
= i < number.length()
? number[number.length() - 1 - i]
- '0'
: 0;
int digit2
= i < other.number.length()
? other.number[other.number.length()
- 1 - i]
- '0'
: 0;
int sum = digit1 + digit2 + carry;
result.push_back(sum % 10 + '0');
carry = sum / 10;
}
// Since the result is reversed, reverse it back to
// get the correct number
reverse(result.begin(), result.end());
return LargeNumber(result);
}
// Overloaded operator<< to print a LargeNumber object
friend ostream& operator<<(ostream& out,
const LargeNumber& num)
{
out << num.number;
return out;
}
};
int main()
{
// Create two LargeNumber objects
LargeNumber num1("123456789012345678901234567890");
LargeNumber num2("987654321098765432109876543210");
// Add the two LargeNumber objects
LargeNumber sum = num1 + num2;
// Print the sum
cout << "Sum: " << sum << endl;
return 0;
}
Output
Sum: 1111111110111111111011111111100
Time Complexity: O(logbaseN), where N is the large number and base is the base of the number system used.
Auxiliary Space: O(logbaseN)
Developers frequently use third party arbitrary precision arithmetic libraries to deal with the limits of built-in types. One such library is the boot::multiprecision library which offers several data types for handling very large numbers for C++.