Friday, December 04, 2009

BigInteger in .NET 4.0

One of the simplest new additions to the .NET 4.0 framework is an integer with arbitrary length, System.Numerics.BigInteger. Here’s a simple usage example, comparing it to a double:

DEFINATION :  The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.

WARNING : Because the BigInteger type is immutable (see Mutability and the BigInteger Structure) and because it has no upper or lower bounds, anOutOfMemoryException can be thrown for any operation that causes a BigInteger value to grow too large.

BigInteger b = BigInteger.Pow(2, 64);

Console.WriteLine("BigInteger: {0}", b.ToString("N"));

Console.WriteLine("Double:     {0}", Math.Pow(2, 64).ToString("N"));

Console.WriteLine();

b = BigInteger.Pow(2, 128);

Console.WriteLine("BigInteger: {0}", b.ToString("N"));

Console.WriteLine("Double:     {0}", ((double)b).ToString("N"));

The output is:

image_284C9F36

No comments: