【问题标题】:Permutation and Combination in C# [closed]C# 中的排列和组合 [关闭]
【发布时间】:2020-01-03 03:39:00
【问题描述】:

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

【问题讨论】:

  • 你只需要nCr和nPr的数量?你有没有尝试过什么?发布它并告诉您卡在哪里。

标签: c# math


【解决方案1】:

我只是为了好玩才去做这件事,这实际上有点挑战性,因为一个幼稚的实现很快就会溢出long。我已将它们包含在 cmets 中。

方程式

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

打印:

720
120

【讨论】:

  • @Richard,不,这不是我所说的幼稚,那将是Factorial(n) / Factorial(n - r),将更新以使其更清晰
  • 明白了!对不起,这也是我的错,英语不是我的母语。
  • // naive: return Factorial(n) / Factorial(r) * Factorial(n - r);应该是 // 天真: return Factorial(n) / (Factorial(r) * Factorial(n - r));
  • 谢谢! @MilinaUdara
  • 使用 FactorialDivision 的解决方案会给出错误的结果。 “朴素”的解决方案速度较慢,但​​给出正确的结果。
猜你喜欢
  • 1970-01-01
  • 2023-03-14
  • 2020-12-12
  • 1970-01-01
  • 2020-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多