Queries for the product of first N factorials | Java 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
import java . io . * ; class GFG { static int MAX = 1000000 ; static int MOD = 10000007 ; static int [ ] result = new int [ MAX + 1 ] ; static int [ ] fact = new int [ MAX + 1 ] ; static void preCompute ( ) { fact [ 0 ] = 1 ; result [ 0 ] = 1 ; for ( int i = 1 ; i <= MAX ; i ++ ) { fact [ i ] = ( ( fact [ i - 1 ] % MOD ) * i ) % MOD ; result [ i ] = ( ( result [ i - 1 ] % MOD ) * ( fact [ i ] % MOD ) ) % MOD ; } } static void performQueries ( int q [ ] , int n ) { preCompute ( ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . println ( result [ q [ i ] ] ) ; } public static void main ( String [ ] args ) { int q [ ] = { 4 , 5 } ; int n = q . length ; performQueries ( q , n ) ; } }