請告訴我如何在C#控制檯應用程序中應用排列和組合,並取N和r的值並計算排列和組合。C#中的排列和組合#
4
A
回答
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
相關問題
- 1. PHP中的組合,部署和排列
- 2. 多種組合和排列中的R
- 3. 數據幀列的組合和排列
- 4. Python中的排列/組合
- 5. 排列組合中的R
- 6. Excel中的排列組合
- 7. 排列組合
- 8. c#按升序排序組合列表
- 9. 列表排列組合
- 10. 有效地計數組合和排列
- 11. Oracle pl/sql排列和組合
- 12. 哈斯克爾組合和排列
- 13. 排列和組合足球比分
- 14. C# - 數字列表的每個6位數組合(排列組合)
- 15. GROUP組合,排列組合不
- 16. 在Matlab中按行排列組合列
- 17. 連續排列組合中的R
- 18. 查詢組合排列
- 19. 改變排列組合(PYTHON)
- 20. 在Java中的Arraylists的排列和組合?
- 21. C中的多數組快速排列
- 22. 從排列中刪除組合
- 23. 在組合框中排列文本
- 24. 幫助在C#中找到快速排列/組合算法
- 25. 組合框在c中重新排列數字1-30#
- 26. 在C#中實現組合和聚合?
- 27. 排序合併數組組成的排序陣列
- 28. 合併和排序列表
- 29. 菜單項的排列組合
- 30. 排列每個組合的字母
你只需要nCr和nPr的數量?你有沒有嘗試過任何東西?張貼並告訴你卡在哪裏。 – weston 2014-10-11 07:12:22