Title: Use the BigInteger structure in C#
The long data type can hold values between roughly 9.2 x 10^{18} and 9.2 x 10^{18}, 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 the example to experiment with it and to see additional details.
