2014-10-11 73 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