Big integers in .NET 4.0

The BigInteger structure becomes available if you add a reference to the System.Numerics namespace. BigInteger represents a positive or negative integer of any size.  This is great for doing arithmetic calculations with very large numbers, and is one of the problems you had to solve on your own in previous versions of .NET Framework.

After the reference is added, you can create a BigInteger using the New keyword, and an initial value can be passed to the constructor, like so:

Dim X As New System.Numerics.BigInteger(Long.MaxValue)
Console.WriteLine(X.ToString())

To do arithmetic operations, create the BigIntegers you need for the operation, and then call the static (shared) functions of the BigInteger structure to do the calculations. In this case, I call the static function Multiply.

Dim X As New System.Numerics.BigInteger(Long.MaxValue)
Dim Y As New System.Numerics.BigInteger(Long.MaxValue)
Dim Z As System.Numerics.BigInteger = _
     System.Numerics.BigInteger.Multiply(X, Y)
Console.WriteLine(Z.ToString())

Just by adding a few of these lines to the above code, will give you one insanely large number.

Z = System.Numerics.BigInteger.Multiply(Z, Z)
Z = System.Numerics.BigInteger.Multiply(Z, Z)
Z = System.Numerics.BigInteger.Multiply(Z, Z)
Z = System.Numerics.BigInteger.Multiply(Z, Z)

One way to serialize this number in SQL Server could be to store the underlying bytes of the number that the BigInteger instance represents. The BigInteger structure has a member function that returns these bytes as a byte array called GetByteArray. An existing byte array can be passed to the constructor of the BigInteger to reconstruct the number.

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll:

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Comments

Important information: If you have not commented before, your comment will be reviewed before it is published. This means that you will not see it immediately, but I have received it. This is not because I want to filter comments, but because I want to prevent spam and advertising.

Leave a Reply

Your email address will not be published. Required fields are marked *