counting combinations and permutations efficiently

后端 未结 13 1954
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 12:38

I have some code to count permutations and combinations, and I\'m trying to make it work better for large numbers.

I\'ve found a better algorithm for permutations th

13条回答
  •  离开以前
    2020-12-02 13:16

    If your problem does not require knowing the exact number of permutations or combinations, then you could use Stirling's approximation for the factorial.

    That would lead to code like this:

    import math
    
    def stirling(n):
        # http://en.wikipedia.org/wiki/Stirling%27s_approximation
        return math.sqrt(2*math.pi*n)*(n/math.e)**n
    
    def npr(n,r):
        return (stirling(n)/stirling(n-r) if n>20 else
                math.factorial(n)/math.factorial(n-r))
    
    def ncr(n,r):    
        return (stirling(n)/stirling(r)/stirling(n-r) if n>20 else
                math.factorial(n)/math.factorial(r)/math.factorial(n-r))
    
    print(npr(3,2))
    # 6
    print(npr(100,20))
    # 1.30426670868e+39
    print(ncr(3,2))
    # 3
    print(ncr(100,20))
    # 5.38333246453e+20
    

提交回复
热议问题