Product of first N factorials | To compute ( a * b ) % MOD ; let res = 0 ; Initialize result ; If b is odd , add ' a ' to result ; Multiply ' a ' with 2 ; Divide b by 2 ; Return result ; This function computes factorials and product by using above function i . e . modular multiplication ; Initialize product and fact with 1 ; ith factorial ; product of first i factorials ; If at any iteration , product becomes divisible by MOD , simply return 0 ; ; Driver Code
function mulmod ( a , b , mod ) { a = a % mod ; while ( b > 0 ) { if ( b % 2 == 1 ) res = ( res + a ) % mod ; a = ( a * 2 ) % mod ; b = parseInt ( b / 2 , 10 ) ; } return res % mod ; } function findProduct ( N ) { let product = 1 , fact = 1 ; let MOD = ( 1e9 + 7 ) ; for ( let i = 1 ; i <= N ; i ++ ) { fact = mulmod ( fact , i , MOD ) ; product = mulmod ( product , fact , MOD ) ; if ( product == 0 ) return 0 ; } return product ; } let N = 3 ; document . write ( findProduct ( N ) + " " ) ; N = 5 ; document . write ( findProduct ( N ) ) ;