Given a number N. Find the product of first N factorials modulo 1000000007.
Constraints: 1 ≤ N ≤ 1e6
Input : 3 Output : 12 Explanation: 1! * 2! * 3! = 12 mod (1e9 + 7) = 12 Input : 5 Output : 34560
Prerequisites: Modular Multiplication
Approach: The basic idea behind solving this problem is to just consider the problem of overflow during multiplication of such large numbers i.e. factorials. Hence, it needs to be addressed by multiplying recursively to overcome the difficulty of overflow. Moreover, we have to take modulus at every step while computing factorials iteratively and modular multiplication.
facti = facti-1 * i where facti is the factorial of ith number prodi = prodi-1 * facti where prodi is the product of first i factorials
To find product of two large numbers under modulo, we use same approach as exponentiation under modulo.. In the multiplication function, we use + instead of *.
Below is the implementation of above approach.
Time Complexity: O(N * logN), where O(log N) is the time complexity of modular multiplication.
- Queries for the product of first N factorials
- Trailing number of 0s in product of two factorials
- GCD of factorials of two numbers
- Find last two digits of sum of N factorials
- Numbers whose factorials end with n zeros
- Find sum of factorials in an array
- Calculating Factorials using Stirling Approximation
- Find the unit place digit of sum of N factorials
- Print factorials of a range in right aligned format
- Check if a given number divides the sum of the factorials of its digits
- Count natural numbers whose factorials are divisible by x but not y
- Program for dot product and cross product of two vectors
- Pandigital Product
- Sum of product of x and y such that floor(n/x) = y
- Cartesian Product of Two Sets
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.