Use the BigInteger structure in C#

[BigInteger]

The long data type can hold values between roughly -9.2 x 1018 and -9.2 x 1018, but sometimes even that range isn’t big enough. The .NET Framework 4.0 (C# 4.0 or Visual Studio 2010) introduced the BigInteger structure to represent integer values of arbitrary size.

To use the BigInteger data type, add a reference to System.Numerics. Then include a using statement to make using the System.Numerics namespace easy.

The following code shows how the example program uses the BigInteger type to calculate large factorials.

// Return N!.
private BigInteger BigFactorial(BigInteger N)
{
    if (N < 0) throw new ArgumentException("N must be at leaat 0.");
    if (N <= 1) return 1;
    BigInteger result = 1;
    for (int i = 2; i <= N; i++) result *= i;
    return result;
}

This code can calculate much larger factorials than it could with the long data type.

Note that the BigInteger type doesn't exist in older versions of the .NET Framework, so the example that's available for download was written in Visual Studio 2012 instead of Visual Studio 2008 as usual.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in mathematics and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

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