2014-10-11 72 views
4

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

+0

你只需要nCr和nPr的数量?你有没有尝试过任何东西?张贴并告诉你卡在哪里。 – weston 2014-10-11 07:12:22

回答

11

我刚开始这样做是为了好玩,它实际上是一个小挑战,因为一个天真的实现非常快速地溢出long。我在评论中包含了这些内容。

方程

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 
+0

@Richard,不,这不是我所说的天真的,那将是'Factorial(n)/ Factorial(n - r)',将更新以使其更清晰 – weston 2014-10-11 09:23:10

+0

明白了!对不起,这也是我的错,英语不是我的母语。 – AFract 2014-10-11 09:29:50

+0

//天真:返回因子(n)/因子(r)*因子(n - r); 应该是//天真:return Factorial(n)/(Factorial(r)* Factorial(n-r)); – 2017-07-06 03:35:04