Home
C#
BigInteger Example
This page was last reviewed on Nov 28, 2023.
Dot Net Perls
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.
double
decimal
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.
An example. 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.
Warning If the program does not compile, try going to "Add Reference" in Visual Studio, and selecting "System.Numerics."
Result For readability, we have omitted the middle part of the 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
Notes, 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.
A summary. Even if you are not focused on numerics, knowing that BigInteger exists and it can be used to store large integers is useful.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 28, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.