Product of first N factorials | To compute ( a * b ) % MOD ; $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
< ? php function mulmod ( $ a , $ b , $ mod ) { $ a = $ a % $ mod ; while ( $ b > 0 ) { if ( $ b % 2 == 1 ) $ res = ( $ res + $ a ) % $ mod ; $ a = ( $ a * 2 ) % $ mod ; $ b /= 2 ; } return $ res % $ mod ; } function findProduct ( $ N ) { $ product = 1 ; $ fact = 1 ; $ MOD = 1000000000 ; for ( $ i = 1 ; $ i <= $ N ; $ i ++ ) { $ fact = mulmod ( $ fact , $ i , $ MOD ) ; $ product = mulmod ( $ product , $ fact , $ MOD ) ; if ( $ product == 0 ) return 0 ; } return $ product ; } $ N = 3 ; echo findProduct ( $ N ) , " STRNEWLINE " ; $ N = 5 ; echo findProduct ( $ N ) , " STRNEWLINE " ; ? >