Binomial Coefficient | DP | Function to find binomial coefficient ; Getting the modular inversion for all the numbers from 2 to r with respect to m here m = 1000000007 ; for 1 / ( r ! ) part ; for ( n ) * ( n - 1 ) * ( n - 2 ) * ... * ( n - r + 1 ) part ; Driver code
def binomialCoeff ( n , r ) : NEW_LINE INDENT if ( r > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT m = 1000000007 NEW_LINE inv = [ 0 for i in range ( r + 1 ) ] NEW_LINE inv [ 0 ] = 1 ; NEW_LINE if ( r + 1 >= 2 ) NEW_LINE inv [ 1 ] = 1 ; NEW_LINE for i in range ( 2 , r + 1 ) : NEW_LINE INDENT inv [ i ] = m - ( m // i ) * inv [ m % i ] % m NEW_LINE DEDENT ans = 1 NEW_LINE for i in range ( 2 , r + 1 ) : NEW_LINE INDENT ans = ( ( ans % m ) * ( inv [ i ] % m ) ) % m NEW_LINE DEDENT for i in range ( n , n - r , - 1 ) : NEW_LINE INDENT ans = ( ( ans % m ) * ( i % m ) ) % m NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 5 NEW_LINE r = 2 NEW_LINE print ( " Value ▁ of ▁ C ( " , n , " , ▁ " , r , " ) ▁ is ▁ " , binomialCoeff ( n , r ) ) NEW_LINE