本文介绍了排列与组合在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请告诉我怎样可以申请排列组合在C#控制台应用程序,并采取N个值和R,并计算排列组合。

Please tell me how can I apply permutation and combination in C# console application and take values of N and r and calculate permutation and combination.

推荐答案

我刚刚有了一个去这样做为了好玩,它实际上是一个小的挑战,一个天真的执行溢出非常快。我已经包括那些评论。

I just had a go doing this for fun, it's actually a little challenge as a naive implementation overflows long very quickly. I've included those in comments.

nPr = n! / (n - r)!
nCr = n! / r! (n - r)!



Implementaion



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



用法



Usage

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



打印:

Prints:

720
120

这篇关于排列与组合在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:14