Title: Calculate multifactorials in C#
I recently stumbled across a mathematical concept that I didn't know about: multifactorials.
The factorial of the number N is written N! and equals N × (N - 1) × (N - 2) ... 2 × 1. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
The double factorial of N is written N!! and equals N × (N - 2) × (N - 3) ... For example, 5!! = 5 × 3 × 1 = 15.
More generally, the Kth factorial of N equals N × (N - K) × (N - 2×K) ... Here are the first three equations.
For another explanation of multifactorials, see the Wolfram Mathworld article Multifactorial and follow the links to the Factorial and Double Factorial articles.
For an even longer explanation including more information such as reasons why you might use multifactorials, see the Wikipedia article Double factorial.
When you click the example's Calculate button, the following code executes.
private void btnCalculate_Click(object sender, EventArgs e)
{
int n = int.Parse(txtN.Text);
lstMultiFactorials.Items.Clear();
// Factorial.
for (int f = 1; f < n; f++)
{
string s = n.ToString() +
new String('!', f) +
" = " +
n.ToString();
long value = n;
for (int i = n - f; i > 0; i -= f)
{
s += " × " + i.ToString();
value *= i;
}
s += " = " + value.ToString("n0");
lstMultiFactorials.Items.Add(s);
}
}
This code gets the number n that you entered. It then makes variable f loop from 1 to n. The value f will represent the number of exclamation marks in n!!! etc.
For each value of f, the program creates a new string s holding n, f exclamation marks, an equals sign, and the number n as in "9!! = 9". The code sets variable value equal to n.
Next the code loops variable i from n - f to 1 decrementing i by f at each step. For example, to calculate 9!!, i loops over the values 9, 7, 5, 3, 1.
Each time through the loop, the code adds the new value of i to the string s and multiples value by i.
After it finishes the i loop, the code adds the result value to the string and displays the final string in the program's list box named lstMultiFactorials.
Download the example to experiment with it and to see additional details.
|