Thursday, September 8, 2011

BigInteger Type in Dotnet 4.0


BigInteger is new numeric type added with Dotnet Framework 4.0. BigInteger type represents large integer value with no upper and lower limits. That’s justifies the use of BigInteger. In general case we can go with BigInteger when we want to perform operation on large value. BigInteger is internally represented as Struct (Value Type). To use BigInteger in application need to add System.Numerics namespace in project.

BigInteger myBigInteger = 1225; //Assign any integer value

Like above assignment of integer to BigInteger type is valid. But most of the cases BigInteger type is used to perform operations on large value so it support some built-in methods to do some common operations like Add, Multiply, Divide, Pow, Max, Min etc. These all operations accept parameter as BigInteger so you can multiply two BigInteger values and so on.

BigInteger provides multiply method using that method we can multiply two BigInteger values. See the below syntax of multiply method of BigInteger.

//Internal syntax of multiply method.
public static BigInteger Multiply(BigInteger left, BigInteger right);

Let’s understand how to use BigIntegers.

BigInteger Total = BigInteger.Multiply(999999999999999,9999999999999999);
Console.WriteLine(Total.ToString()); //Output - 9999999999999989000000000000001

Similar we can use Pow method,

BigInteger Total = BigInteger.Pow(2,100);
Console.WriteLine(Total.ToString()); //Output - 1267650600228229401496703205376

We can implicitly convert any integer value to BigInteger by assigning it to BigInteger but to do reverse need to cast.

int x = 9999;
BigInteger Total = x; //implicit conversion from int to BigInteger
x =(int) Total; //explicit conversion from BigInteger to Int

Note – BigInteger may throw OutOfMemoryException error when the value of BigInteger grows too large. When BigInteger’s value grows extremely large it has measurable performance impact too.

See also - 


No comments:

Post a Comment