Queries for the product of first N factorials | Javascript implementation of the approach ; Declare result array globally ; Function to precompute the product of factorials upto MAX ; Initialize base condition if n = 0 then factorial of 0 is equal to 1 and answer for n = 0 is 1 ; Iterate loop from 1 to MAX ; factorial ( i ) = factorial ( i - 1 ) * i ; Result for current n is equal to result [ i - 1 ] multiplied by the factorial of i ; Function to perform the queries ; Precomputing the result till MAX ; Perform queries ; Driver code
let MAX = 1000000 ; let MOD = 10000007 ; let result = new Array ( MAX + 1 ) ; result . fill ( 0 ) ; let fact = new Array ( MAX + 1 ) ; fact . fill ( 0 ) ; function preCompute ( ) { fact [ 0 ] = 1 ; result [ 0 ] = 1 ; for ( let i = 1 ; i <= MAX ; i ++ ) { fact [ i ] = ( ( fact [ i - 1 ] % MOD ) * i ) % MOD ; result [ i ] = ( ( result [ i - 1 ] % MOD ) * ( fact [ i ] % MOD ) ) % MOD ; } } function performQueries ( q , n ) { preCompute ( ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( result [ q [ i ] ] + " " ) ; } let q = [ 4 , 5 ] ; let n = q . length ; performQueries ( q , n ) ;