BigInteger
For large values, the double
and decimal types are not easy to use. The developer always worries about overflow problems. A better type is needed for big integers.
With the BigInteger
type, we have a special type in .NET that we can use to handle big numbers. We must add a reference to the System.Numerics
assembly first.
Let us begin with this example. It does nothing special, but it adds together 2 values with the maximum value of double
. Our BigInteger
is a "doubled" double
.
BigInteger
results. But we can see the second result appears to be doubled.using System; using System.Numerics; // Create 2 BigIntegers from the maximum value of a double. BigInteger big1 = new BigInteger(double.MaxValue); BigInteger big2 = new BigInteger(double.MaxValue); // Add the 2 values together. BigInteger double1 = BigInteger.Add(big1, big2); // Print the values of the BigIntegers. Console.WriteLine("DOUBLE MAX: " + big1.ToString()); Console.WriteLine("DOUBLE MAX * 2: " + double1.ToString());DOUBLE MAX: 179...(omitted)...368 DOUBLE MAX * 2: 359...(omitted)...736
BigInteger
This is just a sampling of the power of BigInteger
. Usually programs that need BigInteger
will use Multiply, as multiplication tends to yield much larger values than Add.
Even if you are not focused on numerics, knowing that BigInteger
exists and it can be used to store large integers is useful.