【问题标题】:Write a C function called combinations which takes n and r as inputs, and returns the number of combinations编写一个称为组合的 C 函数,它以 n 和 r 作为输入,并返回组合的数量
【发布时间】:2019-10-08 02:57:06
【问题描述】:

从 n 个可能的选择中选择 r 个对象的方法数 顺序称为组合,由 n!/((n-r)!r!) 定义,例如,数字 从 20 个对象中选择 3 个对象的方法是 20! / (17!x3!) = 20x19x18 / 3x2x1 = 1140。 编写一个称为组合的 C 函数,将 n 和 r 作为输入,并返回 组合数。

如果我认为具有两个输入的函数是:

int combinations(int n, int r)
{
//solving combinations here

//return combination
}

我实际上无法弄清楚如何通过函数中的两个输入来解决这个问题,任何帮助将不胜感激。

【问题讨论】:

标签: c


【解决方案1】:

当然,真正的问题是你不能只计算 n!和r!分开,因为阶乘函数增长如此之快即使是那些说“指数”而不知道他们在说什么的人也会低估它:)。相反,你想结合以这样一种方式进行乘法和除法运算,使您可以在没有中间溢出的情况下评估总商数,尽可能大的 n,r 参数。

所以算法才是真正的问题。编码很简单。出于我的目的,我需要二项式权重,即 (n,r)/2^n。所以我描述我的算法的评论块在下面复制,但没有代码,我将留给你。此外,我的算法利用了所有这些额外的 2 因素,这是您无法做到的。所以我在下面给你的只是一个线索,你可能想如何继续......

/****************************************************************************
 * Function:    bweight ( n, i )
 * Purpose:     Calculate [binomial coefficient]/2**n = [n!/(i!(n-i)!)]/2**n.
 * --------------------------------------------------------------------------
 * Arguments:   n (I)           n items...
 *              i (I)           ...taken i at a time
 * Returns:     (double)        as above, or 0 for any argument error
 * --------------------------------------------------------------------------
 * Notes:     o Algorithm prevents dividing one (very) large number
 *              by another.  Note that
 *              n!/(i!(n-i)!) = (n-i+1)(n-i+2)...(n-i+i)/1*2*...*i if i<=n-i,
 *                      or    = (i+1)(i+2)...(i+(n-i))/1*2*...*(n-i) if i>n-i
 *              In both cases the number of terms is the same in the
 *              numerator and denominator, and in both cases it's <=n/2.
 *              Thus, we divide each term by 4=2*2 as we accumulate the
 *              terms.  At the end, we divide by any remaining powers of two
 *              necessary to achieve the total 2**n factor required.  This
 *              helps prevent the numerator from getting too large before
 *              the denominator "cathces up".
 ***************************************************************************/

【讨论】:

    猜你喜欢
    • 2019-10-18
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多