Factorials

28 Feb 2014

C#, Maths


The factorial of an integer is the product of all positive integers less than or equal to that number. A factorial is denoted by the addition of an exclamation mark after the integer. For an integer n that is greater than or equal to 0, n factorial (denoted n!) is defined as:

0! = 1
n! = (n) * (n – 1) * (n – 2) * ... where n > 0

For example, using 10 factorial:

10! = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
=> 10! = 3628800

A list of factorials from 0 to 10 looks like this:

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

Here's a C# extension method you can use to add factorials into your code:


public static int Factorial(this int Value) 
{ 
    int iValue = Value; 

    if (iValue == 0) 
    { 
        iValue = 1; 
    } 
    else 
    { 
        while (Math.Abs(--Value) > 0) 
        { 
            iValue *= Value; 
        } 
    } 

    return iValue; 
} 

 

Copyright © 2024 carlbelle.com