BLOG.CSHARPHELPER.COM: Use the BigInteger structure in C#
Use the BigInteger structure in C#
The long data type can hold values between roughly -9.2 x 1018 and -9.2 x 1018, bit sometimes even that range isn't big enough. The .NET Framework 4.0 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 even extremely large factorials.
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.
Comments