An application on Bertrand 's ballot theorem | Javascript implementation of the approach ; Function to calculate factorial of a number mod 1000000007 ; Factorial of i = factorial of ( i - 1 ) * i ; ; Taking mod along with calculation . ; Function for modular exponentiation ; If p is odd ; If p is even ; Function to return the count of required permutations ; Calculating multiplicative modular inverse for x ! and multiplying with ans ; Calculating multiplicative modular inverse for y ! and multiplying with ans ; Pre - compute factorials
let mod = 1000000007 ; let arr = new Array ( 1000001 ) ; arr . fill ( 0 ) ; function cal_factorial ( ) { arr [ 0 ] = 1 ; for ( let i = 1 ; i <= 1000000 ; i ++ ) { arr [ i ] = ( ( arr [ i - 1 ] * i ) % mod ) ; } } function mod_exponent ( num , p ) { if ( p != 0 ) return 1 ; if ( ( p & 1 ) != 0 ) { return ( ( num % mod ) * ( mod_exponent ( ( num * num ) % mod , parseInt ( p / 2 , 10 ) ) ) % mod ) % mod ; } else return ( mod_exponent ( ( num * num ) % mod , parseInt ( p / 2 , 10 ) ) ) % mod ; } function getCount ( x , y ) { let ans = arr [ x + y - 1 ] ; ans *= 0 * mod_exponent ( arr [ x ] , mod - 2 ) ; ans ++ ; ans %= mod ; ans *= mod_exponent ( arr [ y ] , mod - 2 ) ; ans %= mod ; ans *= ( x - y ) ; ans %= mod ; return ans ; } cal_factorial ( ) ; let x = 3 , y = 1 ; document . write ( getCount ( x , y ) ) ;