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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Queries for the product of first N factorials
- Trailing number of 0s in product of two factorials
- Count natural numbers whose factorials are divisible by x but not y
- Numbers whose factorials end with n zeros
- Calculating Factorials using Stirling Approximation
- GCD of factorials of two numbers
- Print factorials of a range in right aligned format
- Find the unit place digit of sum of N factorials
- Find last two digits of sum of N factorials
- Check if a given number divides the sum of the factorials of its digits
- Find sum of factorials in an array
- Minimum number of Factorials whose sum is equal to N
- Sum of factorials of Prime numbers in a Linked list
- Program for dot product and cross product of two vectors
- First digit in product of an array of numbers
- Find the Product of first N Prime Numbers
- Check if product of first N natural numbers is divisible by their sum
- Product of all Subsets of a set formed by first N natural numbers
- Minimize product of first N - 1 natural numbers by swapping same positioned bits of pairs
- A Product Array Puzzle
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.