VOOZH about

URL: https://www.geeksforgeeks.org/dsa/queries-for-the-product-of-first-n-factorials/

⇱ Queries for the product of first N factorials - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Queries for the product of first N factorials

Last Updated : 13 Mar, 2022

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: 
 


Output: 
288
34560

 

Time Complexity: O(MAX)

Auxiliary Space: O(MAX)

Comment
Article Tags: