Ejmin Mehranian
Ejmin Mehranian

Reputation: 37

integer overflow on c++ and how to add big numbers

I am coding a problem which includes very large numbers. I am having a problem on how to deal with the integer overflow. When I add multiple big numbers I get a negative number. How can i deal with this ? also my data type is

    unsigned long long p=0;

What can I do so it can hold the positive value and continue adding?

Upvotes: 1

Views: 592

Answers (4)

Hiranmay
Hiranmay

Reputation: 1

from [email protected]

You can take advantage of data type int. That can deal any 9 digit number.

Now write a int adder function. Then read 9 digit at a time from input and rest of the execution

Carry will be either 0 or 1. Set carry =1 if s > 9 where s=n1+n2+c1

We can use a completely non numerical approach. Just treat all digit as a symbol.

Case $n1 in 0) case $n2 in 0) case $c1 in 0) s=0; c=0;; 1) s=1; c=0;; esac;; 1) case $c1 in 0) s=1; c=0;; 1) s=2; c=0;; esac;; 2) xxxx 3) xxxx 4) xxxx 5) xxxx 6) xxxx 7) xxxx 8) case $c1 in 0) s=8; c=0;; 1) s=9; c=0;; esac;; 9) case $c1 in 0) s=9; c=0;; 1) s=0; c=1;; esac;; esac;; 1) case $n2 in 0) case $c1 in Xxxxxxxx

Though this code of the function is over 400 line but each cycle will execute only 5-6 line of the code. I would recommend to measure the performance of this code.

Feel free to contact for more details.

Upvotes: 0

Hiranmay
Hiranmay

Reputation: 1

From [email protected]

Write a LongNumber generator using random digit. Then generate one 120 digit and 135 digit inpu.

Write a digit adder function with input = digit1 and digit2 from long number one and two. And carry from last last execution.

Now read one digit from each input and pass those to above function till all digit finished. Concatenation sum digit to result from digit adder.

This is the simplest but not efficient algorithm

Upvotes: 0

Austin Salgat
Austin Salgat

Reputation: 415

If you don't mind losing some precision, you can go with using something like a double (or long double), which can hold arbitrarily large numbers. Since you are using a long long, it sounds like your only option to retain perfect accuracy is to either use a library that implements this or write one yourself, where larger digits would have to be held in another long long that represents those larger digits, and math operations would have to account for storing values larger than long long.

Upvotes: 0

SegFault
SegFault

Reputation: 2546

There are many ways to do this. You could use boost's multi-precision library which could store 128 bit variables.

If you don't want to install other libraries you could always represent your variable in an array where each element is a digit to your variable.

Upvotes: 1

Related Questions