Friday 11 April 2008

Big number calculations in C#

I needed to work with very big numbers (numbers which exceeded int or long types). Imagine for example you need to calculate factorial of 100 or even 1000 or more. How can you do this? The algorithm of factorial calculation is easy but how can you store the result? You can think out solution where you can store your big numbers like strings but solution like this can be difficult to implement. You have to implement own math operation on the string etc.

The other solution is to use F# math library. Because F# is also .NET language you can use it from other .NET languages e.g. C#. So what you need to start? What is necessary to install? F# downloads are available on Microsoft research pages. After you download F# libraries you need to install it and simply create new project in Visual Studio and the FSharp.Core.dll library as reference.

Example calculation of factorial using F# classes:

using System;
using Microsoft.FSharp.Math;

namespace BigNumberCSharp
{
public class TestFactorial
{
public void CalculateFactorial(int x)
{
BigInt factorial = BigIntModule.factorial(BigInt.FromInt32(x));
Console.WriteLine(factorial);
}
}
}


Here is the result for factorial of 100.