VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-handle-large-numbers-in-cpp/

⇱ How to Handle Large Numbers in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Handle Large Numbers in C++?

Last Updated : 23 Jul, 2025

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:


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



Comment