Fastest way to generate binomial coefficients

后端 未结 11 1650
[愿得一人]
[愿得一人] 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条回答
  •  时光说笑
    2020-12-13 03:17

    If I understand the notation in the question, you don't just want nCp, you actually want all of nC1, nC2, ... nC(n-1). If this is correct, we can leverage the following relationship to make this fairly trivial:

    • for all k>0: nCk = prod_{from i=1..k}( (n-i+1)/i )
    • i.e. for all k>0: nCk = nC(k-1) * (n-k+1) / k

    Here's a python snippet implementing this approach:

    def binomial_coef_seq(n, k):
        """Returns a list of all binomial terms from choose(n,0) up to choose(n,k)"""
        b = [1]
        for i in range(1,k+1):
            b.append(b[-1] * (n-i+1)/i)
        return b
    

    If you need all coefficients up to some k > ceiling(n/2), you can use symmetry to reduce the number of operations you need to perform by stopping at the coefficient for ceiling(n/2) and then just backfilling as far as you need.

    import numpy as np
    
    def binomial_coef_seq2(n, k):
        """Returns a list of all binomial terms from choose(n,0) up to choose(n,k)"""
    
        k2 = int(np.ceiling(n/2))
    
        use_symmetry =  k > k2
        if use_symmetry:
            k = k2
    
        b = [1]
        for i in range(1, k+1):
            b.append(b[-1] * (n-i+1)/i)
    
        if use_symmetry:
            v = k2 - (n-k)
            b2 = b[-v:]
            b.extend(b2)
        return b
    

提交回复
热议问题