C#中的排列和组合

请告诉我如何在C#控制台应用程序中应用排列和组合,并获取N和r的值并计算排列和组合。

我只是为了好玩而去做这件事,这实际上是一个小挑战,因为一个天真的实现很快就会溢出。 我在评论中加入了这些内容。

方程

 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); } } 

用法

 Console.WriteLine(PermutationsAndCombinations.nPr(10, 3)); Console.WriteLine(PermutationsAndCombinations.nCr(10, 3)); 

打印:

 720 120