Manipulating Huge Integers In C#


Introduction

In this blog we will see how to work with big integers. In lot of cases we required to manipulate the big inter numbers and finally we have only capacity of work still 19 digits by using Int64. Until .Net Framework version 3.5 we have to use only max Int64 but in .Net framework version 4.0 we got one more new struct using System.Numerics.BigInteger. Using this struct we are able to manipulate big integers, doubles, bytes and decimal values. Using biginteger we are able perform the calculations on the numbers which are more than 50 digits also.

In last cases like Int64 we if we pass more than 19 digits it's throws an error either input string too long or too short but using new struct i.e. BigInteger you can pass more than 50 also. So let's see some operations of using this new biginteger.

Example 1 : Addition

Using biginteger you can make addition of more than 50 digits also and this biginteger struct only provide the Add method which takes two biginteger values and returns the biginteger try it like bellow.

public BigInteger addHugeIntegers(BigInteger a, BigInteger b)
{
     return BigInteger.Add(a, b);
}

Example 2 :  Subtract

BigInteger provide the Subtract method using you can make subtraction in two huge integer values like bellow.

public BigInteger subtractHughIntegers(BigInteger a,BigInteger b)
{
     return BigInteger.Subtract(a, b);
}


Example 3 : Compare

Biginteger is able to compare two values also like first value is greater than or equal to or less than etc… like bellow.

public int Compare(BigInteger a, BigInteger b)
{
     return BigInteger.Compare(a, b);
}


Example 4 : EqualTo:

Biginteger is able to check the two values are equal or not equal to and return the bool true if they are equal and returns false if they are not equal like bellow.

public bool isEqualTo(BigInteger a,BigInteger b)
{
     return BigInteger.Equals(a,b);
}


Our biginteger having more methods also which takes input as Double, Decimal and bytes also for more you can refer MSDN. But remind the biginteger supports only Vista SP1, 7, xp sp3 and server 2008/R2, Server 2003 Sp2 these versions of os are supported by BigInteger.

Conclusion

Using BigInteger in .Net 4.0 we are able to manipulate huge integers which may have more than 50 digits also.
Ebook Download
View all
Learn
View all