3

i am trying to figure out how to handle overflow for addition, subtraction, multiplication and division, for two very large integer numbers. Any feedback/input would be appreciated. Does anyone know any algorithms for this and/or sources I could consult?

(I have done research before posting and am just not sure how to tackle this and)

EDIT: for two very large integer numbers

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79
Masterminder
  • 1,127
  • 7
  • 21
  • 31
  • 3
    What do you mean by handle? Throw an error, return a certain number (e.g. 0), or use bigger numbers so there is no overflow? – Serdalis Nov 14 '12 at 03:55
  • which big number library are you using? check **the documentation** – Cheers and hth. - Alf Nov 14 '12 at 03:55
  • Just to clarify: are you asking "How can I know when a (floating-point) addition/subtraction/multiplication/division operation will overflow, and what are the usual methods for dealing with such cases?" – Brian L Nov 14 '12 at 04:54
  • k well when you add two very large numbers there is overflow, so I am asking how you would handle this. Is that a cleareR? – Masterminder Nov 14 '12 at 05:08
  • @Serdalis by overflow i mean to handle it so it does not go pass the bounds. Okay suppose I would have fractions. 2/3 + 1/2 is a case now imagine the numerators have very large numbers and you are adding them how would you handle this to prevent overflow? – Masterminder Nov 14 '12 at 05:16

4 Answers4

0

This seems to be similar to the questions Check for overflow condition in an arithmetic operation and How to detect integer overflow?

Community
  • 1
  • 1
kameswarib
  • 133
  • 7
0

If you want to avoid the condition of overflow occurring, one way would be to use a linked list to store parts of a number and then perform calculations on the parts individually, and add more nodes to the list to handle the excess digits when needed.

Example

1234567890 can be stored as -> 12,34,56,78,90 To multiply, each unit will be multiplied and carry taken over to next unit -> 1,23,45,67,89,0

Keep in mind though, that it is easier to divide it into single digit units, like 1,2,3,4,5 rather than 1,23,45 as this makes the operations simpler.

EDIT :: The word "handle" is not the word you should be using

asheeshr
  • 4,088
  • 6
  • 31
  • 50
0

Because an integer divided by an integer is rarely an integer, this is impossible in general.

That said, this is what I think you want: http://gmplib.org/

It handles integers and rationals of arbitrary size.

Alexander Duchene
  • 1,107
  • 1
  • 11
  • 14
0

If you wonder how you can check overflows, I would recommend this:

log(a) + log(b) = log(a*b)
  • Correct => no overflow
  • Not correct => overflow

(... and now fingers crossed that nobody finds a contra-example and please, don't start about negative numbers, this is a uint approach).

Dominique
  • 16,450
  • 15
  • 56
  • 112