Fastest way to generate binomial coefficients

后端 未结 11 1785
[愿得一人]
[愿得一人] 2020-12-13 02:20

I need to calculate combinations for a number.

What is the fastest way to calculate nCp where n>>p?

I need a fast way to generate binomial coefficients for a

11条回答
  •  猫巷女王i
    2020-12-13 03:18

    The fastest reasonable approximation in my own benchmarking is the approximation used by the Apache Commons Maths library: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/special/Gamma.html#logGamma(double)

    My colleagues and I tried to see if we could beat it, while using exact calculations rather than approximates. All approaches failed miserably (many orders slower) except one, which was 2-3 times slower. The best performing approach uses https://math.stackexchange.com/a/202559/123948, here is the code (in Scala):

    var i: Int = 0
    var binCoeff: Double = 1
    while (i < k) {
      binCoeff *= (n - i) / (k - i).toDouble
      i += 1
    }
    binCoeff
    

    The really bad approaches where various attempts at implementing Pascal's Triangle using tail recursion.

提交回复
热议问题