Queries of nCr%p in O(1) time complexity

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.

Constraints:

N <= 106
R <= 106
p is a prime number

Examples:

Input:
Q = 2 p = 1000000007
1st query: N = 15, R = 4
2nd query: N = 20, R = 3
Output:
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:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to answer queries
// of nCr in O(1) time.
#include <bits/stdc++.h>
#define ll long long
const int N = 1000001;
using namespace std;
  
// array to store inverse of 1 to N
ll factorialNumInverse[N + 1];
  
// array to precompute inverse of 1! to N!
ll naturalNumInverse[N + 1];
  
// array to store factorial of first N numbers
ll fact[N + 1];
  
// Function to precompute inverse of numbers
void InverseofNumber(ll p)
{
    naturalNumInverse[0] = naturalNumInverse[1] = 1;
    for (int i = 2; i <= N; i++)
        naturalNumInverse[i] = naturalNumInverse[p % i] * (p - p / i) % p;
}
// Function to precompute inverse of factorials
void InverseofFactorial(ll p)
{
    factorialNumInverse[0] = factorialNumInverse[1] = 1;
  
    // precompute inverse of natural numbers
    for (int i = 2; i <= N; i++)
        factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p;
}
  
// Function to calculate factorial of 1 to N
void factorial(ll p)
{
    fact[0] = 1;
  
    // precompute factorials
    for (int i = 1; i <= N; i++) {
        fact[i] = (fact[i - 1] * i) % p;
    }
}
  
// Function to return nCr % p in O(1) time
ll Binomial(ll N, ll R, ll p)
{
    // n C r = n!*inverse(r!)*inverse((n-r)!)
    ll ans = ((fact[N] * factorialNumInverse[R])
              % p * factorialNumInverse[N - R])
             % p;
    return ans;
}
  
// Driver Code
int main()
{
    // Calling functions to precompute the
    // required arrays which will be required
    // to answer every query in O(1)
    ll p = 1000000007;
    InverseofNumber(p);
    InverseofFactorial(p);
    factorial(p);
  
    // 1st query
    ll N = 15;
    ll R = 4;
    cout << Binomial(N, R, p) << endl;
  
    // 2nd query
    N = 20;
    R = 3;
    cout << Binomial(N, R, p) << endl;
  
    return 0;
}

chevron_right


Python3

# Python 3 program to answer queries
# of nCr in O(1) time.
N = 1000001

# array to store inverse of 1 to N
factorialNumInverse = [None] * (N + 1)

# array to precompute inverse of 1! to N!
naturalNumInverse = [None] * (N + 1)

# array to store factorial of
# first N numbers
fact = [None] * (N + 1)

# Function to precompute inverse of numbers
def InverseofNumber(p):
naturalNumInverse[0] = naturalNumInverse[1] = 1
for i in range(2, N + 1, 1):
naturalNumInverse[i] = (naturalNumInverse[p % i] *
(p – int(p / i)) % p)

# Function to precompute inverse
# of factorials
def InverseofFactorial(p):
factorialNumInverse[0] = factorialNumInverse[1] = 1

# precompute inverse of natural numbers
for i in range(2, N + 1, 1):
factorialNumInverse[i] = (naturalNumInverse[i] *
factorialNumInverse[i – 1]) % p

# Function to calculate factorial of 1 to N
def factorial(p):
fact[0] = 1

# precompute factorials
for i in range(1, N + 1):
fact[i] = (fact[i – 1] * i) % p

# Function to return nCr % p in O(1) time
def Binomial(N, R, p):

# n C r = n!*inverse(r!)*inverse((n-r)!)
ans = ((fact[N] * factorialNumInverse[R])% p *
factorialNumInverse[N – R])% p
return ans

# Driver Code
if __name__ == ‘__main__’:

# Calling functions to precompute the
# required arrays which will be required
# to answer every query in O(1)
p = 1000000007
InverseofNumber(p)
InverseofFactorial(p)
factorial(p)

# 1st query
N = 15
R = 4
print(Binomial(N, R, p))

# 2nd query
N = 20
R = 3
print(Binomial(N, R, p))

# This code is contributed by
# Surendra_Gangwar

Output:

1365
1140

Time Complexity: O(106) for precomputing and O(1) for every query.



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.



Improved By : SURENDRA_GANGWAR