How to calculate Space and time efficient Binomial Coefficient in Python
In this tutorial, we are going to write a program that helps us find Space and Time-efficient of a Binomial coefficient in Python.
The code should take two parameters and return the binomial coefficient.
For example, the code should accept two values which may be 16 and 4 and should return to 1820.
The standard calculation Algorithm follows the following binomial structure to give the desired result,
C(n, k) = n! / (n-k)! * k! = [n * (n-1) *....* 1] / [ ( (n-k) * (n-k-1) * .... * 1) * ( k * (k-1) * .... * 1 ) ]
After simplifying, we get C(n, k) = [n * (n-1) * .... * (n-k+1)] / [k * (k-1) * .... * 1] Also, C(n, k) = C(n, n-k)
We can change r to n-r if r > n-r
This standard procedure when encoded helps us calculate the coefficient with just a simple click.
Python program to calculate Space and time-efficient Binomial Coefficient
# Returns value of Binomial Coefficient
# C(m, k)
def binomial_Coefficient(m, k):
# C(m, k) = C(m, m - k)
if(k > m - k):
k = m - k
#Result
result = 1
#Calculate
for j in range(k):
result = result * (m - j)
result = result / (j + 1)
return result
#Driver
m = 16
k = 4
res = binomial_Coefficient(m, k)
print("Value of C(%d, %d) is %d" %(m, k, res))
Output
Value of C(16, 4) is 1820
Leave a Reply