Calculate the factorial function and use Debug.Assert in C#

factorial function

The factorial of a number N is written N! and has the value 1 * 2 * 3 * … * N. By definition, 0! = 1.

The value N! gives the number of permutations of a set of N objects. For example, if you have 5 objects, then you can arrange them in 5! = 1 * 2 * 3 * 4 * 5 = 120 different orders.

Calculating the factorial of a number N is fairly easy. Simply set a result variable equal to 1 and multiply it by the integers between 2 and N.

// Calculate N!
private decimal Factorial(decimal N)
{
    Debug.Assert(N >= 0);

    decimal result = 1;
    for (decimal i = 2; i <= N; i++) result *= i;            
    return result;
}

One thing about this code deserves special mention: the Debug.Assert statement. The Debug class is in the System.Diagnostics namespace, so the example program includes the following using statement to make using the class easier.

using System.Diagnostics;

When you run the debug version of the program, the Debug.Assert statement checks a boolean expression and throws an exception if the expression is false. Optional parameters let you specify things such as the error message the exception should include.

When you run the release version of the program, this statement is removed. It doesn’t run and doesn’t even take up space in the compiled program. This lets you test for errors while you are building your application, and then remove those tests to improve performance in the release build.

Debug.Assert can help you pinpoint bugs quickly without hurting performance in the release build, so I whole-heartedly recommend that you use it for sanity checks in your code. For example, you can use it to make sure function parameters make sense and that calculated results look correct.


Download Example   Follow me on Twitter   RSS feed


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

Leave a Reply

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