I have to store an integer value that is larger than the maximum value for the long datatype. How would I store and manipulate this value in memory?
Please illustrate it through an example, if possible.
Below are the steps: Take the large number as input and store it in a string. Create an integer array arr[] of length same as the string size. Iterate over all characters (digits) of string str one by one and store that digits in the corresponding index of the array arr.
(Arithmetic) Integer Overflows An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).
The long data type stores integers like int , but gives a wider range of values at the cost of taking more memory. Long stores at least 32 bits, giving it a range of -2,147,483,648 to 2,147,483,647.
In C++, we can use large numbers by using the boost library. This C++ boost library is widely used library. This is used for different sections. It has large domain of applications.
Think about storing a numbers as sequences of decimal digits using a struct like this:
struct num {
int ndigits;
char d[MAXDIGITS];
};
For example, the number 123456 could be initialized as
struct num n = { 6, { 6, 5, 4, 3, 2, 1 } };
The reversed digit order turns out to be important for easy calculation. In particular, the place value of n.d[i]
is n.d[i]
* 10^i.
Now, a few questions:
num
?num
?num
s together?num
by two?num
by a single digit?num
by 10?num
s together? HINT: Do some pencil and paper multiplications and see how they work.If you work through this sequence of questions, you should be able to write a function for each step, and re-use those functions to answer the later questions, and end up with a very simple and unoptimized long (well, up to MAXDIGIT
digits) integer package for addition and multiplication of positive numbers.
Other questions:
num
to represent negative numbers as well as positive?num
by another (ignoring remainders)? This is trickier than multiplication, but again, start by doing a few pencil and paper long divisions and think carefully about what you do.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With