Please tell me how can I apply permutation and combination in C# console application and take values of N and r and calculate permutation and combination.
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.
nPr = n! / (n - r)!
nCr = n! / r! (n - r)!
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);
}
}
Console.WriteLine(PermutationsAndCombinations.nPr(10, 3));
Console.WriteLine(PermutationsAndCombinations.nCr(10, 3));
Prints:
720
120
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With