Open In App

How to Handle Large Numbers in C++?

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, when working with very large numbers the standard data types like int can become insufficient due to their limited range. In this article, we will learn how we can handle large numbers in C++.

Handle Large Numbers in C++

To store integers of different sizes, C++ offers built-in data types like int, long, and long long. Following are the range of values that can be stored in these data types:

int :  -2,147,483,648 to 2,147,483,647
long : -2,147,483,648 to 2,147,483,647
long long: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Overflow and underflow problems can arise when working with numbers that are outside of the built-in types’ range, causing unexpected behavior in applications. The long long data type has a larger range than the regular int and long types however this range can still be insufficient for certain applications that require even larger numeric values.

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++
// 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++.





Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads