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 to Test above functions
def mulmod ( a , b , mod ) : NEW_LINE INDENT a = a % mod NEW_LINE while ( b > 0 ) : NEW_LINE INDENT if ( b % 2 == 1 ) : NEW_LINE INDENT res = ( res + a ) % mod NEW_LINE DEDENT a = ( a * 2 ) % mod NEW_LINE b //= 2 NEW_LINE DEDENT return res % mod NEW_LINE DEDENT def findProduct ( N ) : NEW_LINE INDENT product = 1 ; fact = 1 NEW_LINE MOD = 1e9 + 7 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT fact = mulmod ( fact , i , MOD ) NEW_LINE product = mulmod ( product , fact , MOD ) NEW_LINE if not product : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return int ( product ) NEW_LINE DEDENT N = 3 NEW_LINE print ( findProduct ( N ) ) NEW_LINE N = 5 NEW_LINE print ( findProduct ( N ) ) NEW_LINE