![]() |
VOOZH | about |
Given Q[] queries where each query consists of an integer N, the task is to find the product of first N factorials for each of the query. Since the result could be large, compute it modulo 109 + 7.
Examples:
Input: Q[] = {4, 5}
Output:
288
34560
Query 1: 1! * 2! * 3! * 4! = 1 * 2 * 6 * 24 = 288
Query 2: 1! * 2! * 3! * 4! * 5! = 1 * 2 * 6 * 24 * 120 = 34560
Input: Q[] = {500, 1000, 7890}
Output:
976141892
560688561
793351288
Approach: Create two arrays result[] and fact[] where fact[i] will store the factorial of i and result[i] will store the product of first i factorial.
Initialise fact[0] = 1 and result[0] = 1. Now for the rest of the values, the recurrence relation will be:
fact[i] = fact[i - 1] * i
result[i] = result[i - 1] * fact[i]
Now, each query can be answered using the result[] array generated.
Below is the implementation of the above approach:
288 34560
Time Complexity: O(MAX)
Auxiliary Space: O(MAX)