Product of first N factorials | Java Program to find the product of first N factorials ; To compute ( a * b ) % MOD ; long 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
class GFG { static double mulmod ( long a , long b , long mod ) { a = a % mod ; while ( b > 0 ) { if ( b % 2 == 1 ) res = ( res + a ) % mod ; a = ( a * 2 ) % mod ; b /= 2 ; } return res % mod ; } static long findProduct ( long N ) { long product = 1 , fact = 1 ; long MOD = ( long ) ( 1e9 + 7 ) ; for ( int i = 1 ; i <= N ; i ++ ) { fact = ( long ) mulmod ( fact , i , MOD ) ; product = ( long ) mulmod ( product , fact , MOD ) ; if ( product == 0 ) return 0 ; } return product ; } public static void main ( String [ ] args ) { long N = 3 ; System . out . println ( findProduct ( N ) ) ; N = 5 ; System . out . println ( findProduct ( N ) ) ; } }