Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between two large numbers C#

There are already solutions to this problem for small numbers:

  • Here: Difference between 2 numbers
  • Here: C# function to find the delta of two numbers
  • Here: How can I find the difference between 2 values in C#?

I'll summarise the answer to them all:

Math.Abs(a - b)

The problem is when the numbers are large this gives the wrong answer (by means of an overflow). Worse still, if (a - b) = Int32.MinValue then Math.Abs crashes with an exception (because Int32.MaxValue = Int32.MinValue - 1):

System.OverflowException occurred
HResult=0x80131516
Message=Negating the minimum value of a twos complement number is invalid.
Source=mscorlib
StackTrace: at System.Math.AbsHelper(Int32 value) at System.Math.Abs(Int32 value)

Its specific nature leads to difficult-to-reproduce bugs.

Maybe I'm missing some well known library function, but is there any way of determining the difference safely?

like image 962
c z Avatar asked Feb 07 '23 11:02

c z


1 Answers

As suggested by others, use BigInteger as defined in System.Numerics (you'll have to include the namespace in Visual Studio) Then you can just do:

BigInteger a = new BigInteger();
BigInteger b = new BigInteger();
// Assign values to a and b somewhere in here...
// Then just use included BigInteger.Abs method
BigInteger result = BigInteger.Abs(a - b);

Jeremy Thompson's answer is still valid, but note that the BigInteger namespace includes an absolute value method, so there shouldn't be any need for special logic. Also, Math.Abs expects a decimal, so it will give you grief if you try to pass in a BigInteger.

Keep in mind there are caveats to using BigIntegers. If you have a ludicrously large number, C# will try to allocate memory for it, and you may run into out of memory exceptions. On the flip side, BigIntegers are great because the amount of memory allotted to them is dynamically changed as the number gets larger.

Check out the microsoft reference here for more info: https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx

like image 125
Verbal Kint Avatar answered Feb 12 '23 12:02

Verbal Kint