Calculate factorials (and use Debug.Assert) in in C#

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! = 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 numbers 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 program includes a using statement to make using it easier.

When you run the debug version of the program, this statement checks a Boolean expression and throws an error 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 but then remove those tests to improve performance in the release build.

Debug.Assert can help you pinpoint bugs quickly without hurting performance in the releaser 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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.