Given Q queries and P where P is a prime number, each query has two numbers N and R and the task is to calculate nCr mod p.
N <= 106 R <= 106 p is a prime number
Q = 2 p = 1000000007
1st query: N = 15, R = 4
2nd query: N = 20, R = 3
1st query: 1365
2nd query: 1140
15!/(4!*(15-4)!)%1000000007 = 1365
20!/(20!*(20-3)!)%1000000007 = 1140
A naive approach is to calculate nCr using formulae by applying modular operations at any time. Hence time complexity will be O(q*n).
A better approach is to use fermat little theorem. According to it nCr can also be written as (n!/(r!*(n-r)!) ) mod which is equivalent to (n!*inverse(r!)*inverse((n-r)!) ) mod p. So, precomputing factorial of numbers from 1 to n will allow queries to be answered in O(log n). The only calculation that needs to be done is calculating inverse of r! and (n-r)!. Hence overall complexity will be q*( log(n)) .
A efficient approach will be to reduce the better approach to an efficient one by precomputing the inverse of factorials. Precompute inverse of factorial in O(n) time and then quereies can be answered in O(1) time. Inverse of 1 to N natural number can be computed in O(n) time using Modular multiplicative inverse. Using recursive definition of factorial, the following can be written:
n! = n * (n-1) ! taking inverse on both side inverse( n! ) = inverse( n ) * inverse( (n-1)! )
Since N’s maximum value is 106, precomputing values till 106 will do.
Below is the implementation of the above approach:
Time Complexity: O(106) for precomputing and O(1) for every query.
- How is the time complexity of Sieve of Eratosthenes is n*log(log(n))?
- Extended Mo's Algorithm with ≈ O(1) time complexity
- Cyclomatic Complexity
- Complexity Analysis of Binary Search
- Maximum removal from array when removal time >= waiting time
- XOR of a submatrix queries
- Queries for the product of first N factorials
- Range and Update Sum Queries with Factorial
- Subset Sum Queries in a Range using Bitset
- Perform the given queries on the rooted tree
- Queries for number of array elements in a range with Kth Bit Set
- Queries to check whether a given digit is present in the given Range
- Range Sum Queries and Update with Square Root
- Queries for number of distinct integers in Suffix
- Range Queries to Find number of sub-arrays with a given xor
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.
Improved By : SURENDRA_GANGWAR