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
function binomialCoeff ( n , r ) { if ( r > n ) return 0 ; let m = 1000000007 ; let inv = new Array ( r + 1 ) . fill ( 0 ) ; inv [ 0 ] = 1 ; if ( r + 1 >= 2 ) inv [ 1 ] = 1 ; for ( let i = 2 ; i <= r ; i ++ ) { inv [ i ] = m - Math . floor ( m / i ) * inv [ m % i ] % m ; } let ans = 1 ; for ( let i = 2 ; i <= r ; i ++ ) { ans = ( ( ans % m ) * ( inv [ i ] % m ) ) % m ; } for ( let i = n ; i >= ( n - r + 1 ) ; i -- ) { ans = ( ( ans % m ) * ( i % m ) ) % m ; } return ans ; } let n = 5 , r = 2 ; document . write ( " " + n + " " + r + " " + binomialCoeff ( n , r ) + " " ) ;