[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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, 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 least 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.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.