Binomial Coefficient | DP | Function to find gcd of two numbers in O ( log ( min ( a , b ) ) ) ; Base case ; C ( n , r ) = C ( n , n - r ) better time complexity for lesser r value ; Array of elements from n - r + 1 to n ; For numbers from 1 to r find arr [ j ] such that gcd ( i , arr [ j ] ) > 1 ; If gcd > 1 , divide both by gcd ; If i becomes 1 , no need to search arr ; Single pass to multiply the numerator ; Driver code
function gcd ( a , b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } function nCr ( n , r ) { if ( r > n ) return 0 ; if ( r > n - r ) r = n - r ; mod = 1000000007 ; var arr = new Array ( r ) ; for ( var i = n - r + 1 ; i <= n ; i ++ ) { arr [ i + r - n - 1 ] = i ; } var ans = 1 ; for ( var k = 1 ; k < r + 1 ; k ++ ) { var j = 0 , i = k ; while ( j < arr . length ) { var x = gcd ( i , arr [ j ] ) ; if ( x > 1 ) { arr [ j ] /= x ; i /= x ; } if ( i == 1 ) break ; j += 1 ; } } arr . forEach ( function ( i ) { ans = ( ans * i ) % mod ; } ) ; return ans ; } var n = 5 , r = 2 ; document . write ( " " + n + " " + r + " " + nCr ( n , r ) + " " ) ;