两种方法计算组合数C#程序

  ///


        /// 快速计算组合数
        ///

        ///
        ///
        ///
        private UInt64  calcCombinQuick(int n, int m)
        {
            if(m==n)            return 1;
            if (n == 0) return 1;
            if (n == 1) return (UInt64)m;
            int[] sn = new int[n];
            int[] tn = new int[n];
            UInt64 times=1;
            int temp = 1;
            for (int i = 0; i < n; i++)
            {
                sn[i] = m - i;
                tn[i] = i + 1;
            }
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    temp=calcGreatestCommonDivisor(sn[i],tn[j]);
                    if (temp > 1)
                    {
                        sn[i] = sn[i] / temp;
                        tn[j] = tn[j] / temp;
                    }
                }
                times *= (UInt64)sn[i];
            }
            return times;

        }
        ///


        /// 计算最大公约数
        ///

        ///
        ///
        /// 最大公约数
        private int calcGreatestCommonDivisor(int v, int u)
        {
            int t = 1;
            int r;
            if (v > u)
            { t = u; u = v; v = t; }
            while ((r = u % v) != 0)
            {
                u = v;
                v = r;
            }
            return (v);

        }
        ///


        /// 递归法计算组合数,不过很慢的
        ///

        ///
        ///
        ///
        private UInt64  calccombin(int mm, int nn)
        {
            if (( nn == 0)||(mm==nn)) return 1;
            return calccombin(mm - 1, nn - 1) + calccombin(mm-1, nn);
        }

你可能感兴趣的:(c#)