I just had a go doing this for fun, it's actually a little challenging as a naive implementation overflows long
very quickly. I've included those in comments.
Equations
nPr = n! / (n - r)!
nCr = n! / r! (n - r)!
Implementaion
public static class PermutationsAndCombinations
{
public static long nCr(int n, int r)
{
// naive: return Factorial(n) / (Factorial(r) * Factorial(n - r));
return nPr(n, r) / Factorial(r);
}
public static long nPr(int n, int r)
{
// naive: return Factorial(n) / Factorial(n - r);
return FactorialDivision(n, n - r);
}
private static long FactorialDivision(int topFactorial, int divisorFactorial)
{
long result = 1;
for (int i = topFactorial; i > divisorFactorial; i--)
result *= i;
return result;
}
private static long Factorial(int i)
{
if (i <= 1)
return 1;
return i * Factorial(i - 1);
}
}
Usage
Console.WriteLine(PermutationsAndCombinations.nPr(10, 3));
Console.WriteLine(PermutationsAndCombinations.nCr(10, 3));
Prints:
720
120