How to Handle Large Numbers in C++?
Last Updated :
16 Apr, 2024
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;
}
OutputSum: 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++.
Similar Reads
How to Find Largest Number in an Array in C++?
In C++, arrays are used to store the collection of similar elements to be stored in adjacent memory locations. They can store data of any type such as int, char, float, etc. In this article, we will learn how to find the largest number in an array in C++. For Example,Input: myVector = {1, 3, 10, 7,
2 min read
Largest and smallest digit of a number
Given a number N. The task is to find the largest and the smallest digit of the number.Examples : Input : N = 2346 Output : 6 2 6 is the largest digit and 2 is smallestInput : N = 5 Output : 5 5 Approach: An efficient approach is to find all digits in the given number and find the largest and the sm
7 min read
How to store a very large number of more than 100 digits in C++
Given an integer N in form of string str consisting of more than 100 digits, the task is to store the value for performing an arithmetic operation and print the given integer.Examples: Input: str = "54326789013892014531903492543267890138920145319034925432678901389201" Output: 54326789013892014531903
3 min read
How to Handle Wrong Data Type Input in C++?
In C++, when weâre expecting a certain type of input but the user enters a different type then such input is called incorrect data input and it can cause issues like unexpected behavior, program failures, or inaccurate results. In this article, we will learn how to handle wrong data type input in C+
2 min read
Generate Random Double Numbers in C++
Double is a data type just like a float but double has 2x more precision than float. One bit for the sign, 11 bits for the exponent and 52* bits for the value constitute the 64-bit IEEE 754 double precision Floating Point Number known as "double." Double has 15 decimal digits of precision. In this a
2 min read
How to Round a Double to an int in C++?
In C++, the double data type is used to store floating-point numbers with double precision. In this article, we will learn how to round a double value to an int in C++. Example: Input: double val= 2.6 Output: Integer for double value 2.5 is: 3 Rounding a Double to an Int in C++To round a double valu
2 min read
How Can I Efficiently Sort a Large Array in C++?
In C++, sorting an array means rearranging the elements of an array in a logical order. In this article, we will learn how to efficiently sort a large array in C++. Example: Input: myArray = {5, 2, 3, 1, 4......};Output: Sorted array is : 1 2 3 4 5 ....Sorting a Very Large Array in C++ To efficientl
2 min read
How to Use the ignore() Function in C++?
In C++, the ignore() function is a part of std::basic_istream that is used to discard the characters in the stream until the given delimiter(including it) is reached and then extracts the left-out remainder. In this article, we will learn how to use the ignore() function in C++. C++ ignore() Functio
2 min read
C++ Program For char to int Conversion
In C++, we cannot directly perform numeric operations on characters that represent numeric values. If we attempt to do so, the program will interpret the character's ASCII value instead of the numeric value it represents. We need to convert the character into an integer.Example:Input: '9'Output: 9Ex
2 min read
C++ Program For int to char Conversion
In this article, we will learn how to convert int to char in C++. For this conversion, there are 5 ways as follows: Using typecasting.Using static_cast.Using sprintf().Using to_string() and c_str().Using stringstream. Let's start by discussing each of these methods in detail. Examples: Input: N = 65
6 min read