Queries of nCr%p in O(1) time complexity
Last Updated :
11 Jul, 2025
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 queries 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++
// 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;
}
Java
// Java program to answer queries
// of nCr in O(1) time
import java.io.*;
class GFG{
static int N = 1000001;
// Array to store inverse of 1 to N
static long[] factorialNumInverse = new long[N + 1];
// Array to precompute inverse of 1! to N!
static long[] naturalNumInverse = new long[N + 1];
// Array to store factorial of first N numbers
static long[] fact = new long[N + 1];
// Function to precompute inverse of numbers
public static void InverseofNumber(int p)
{
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for(int i = 2; i <= N; i++)
naturalNumInverse[i] = naturalNumInverse[p % i] *
(long)(p - p / i) % p;
}
// Function to precompute inverse of factorials
public static void InverseofFactorial(int 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
public static void factorial(int p)
{
fact[0] = 1;
// Precompute factorials
for(int i = 1; i <= N; i++)
{
fact[i] = (fact[i - 1] * (long)i) % p;
}
}
// Function to return nCr % p in O(1) time
public static long Binomial(int N, int R, int p)
{
// n C r = n!*inverse(r!)*inverse((n-r)!)
long ans = ((fact[N] * factorialNumInverse[R]) %
p * factorialNumInverse[N - R]) % p;
return ans;
}
// Driver code
public static void main (String[] args)
{
// Calling functions to precompute the
// required arrays which will be required
// to answer every query in O(1)
int p = 1000000007;
InverseofNumber(p);
InverseofFactorial(p);
factorial(p);
// 1st query
int n = 15;
int R = 4;
System.out.println(Binomial(n, R, p));
// 2nd query
n = 20;
R = 3;
System.out.println(Binomial(n, R, p));
}
}
// This code is contributed by RohitOberoi
Python3
# Python3 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
C#
// C# program to answer queries
// of nCr in O(1) time
using System;
class GFG{
static int N = 1000001;
// Array to store inverse of 1 to N
static long[] factorialNumInverse = new long[N + 1];
// Array to precompute inverse of 1! to N!
static long[] naturalNumInverse = new long[N + 1];
// Array to store factorial of first N numbers
static long[] fact = new long[N + 1];
// Function to precompute inverse of numbers
static void InverseofNumber(int p)
{
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for(int i = 2; i <= N; i++)
naturalNumInverse[i] = naturalNumInverse[p % i] *
(long)(p - p / i) % p;
}
// Function to precompute inverse of factorials
static void InverseofFactorial(int 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
static void factorial(int p)
{
fact[0] = 1;
// Precompute factorials
for(int i = 1; i <= N; i++)
{
fact[i] = (fact[i - 1] * (long)i) % p;
}
}
// Function to return nCr % p in O(1) time
static long Binomial(int N, int R, int p)
{
// n C r = n!*inverse(r!)*inverse((n-r)!)
long ans = ((fact[N] * factorialNumInverse[R]) %
p * factorialNumInverse[N - R]) % p;
return ans;
}
// Driver code
static void Main()
{
// Calling functions to precompute the
// required arrays which will be required
// to answer every query in O(1)
int p = 1000000007;
InverseofNumber(p);
InverseofFactorial(p);
factorial(p);
// 1st query
int n = 15;
int R = 4;
Console.WriteLine(Binomial(n, R, p));
// 2nd query
n = 20;
R = 3;
Console.WriteLine(Binomial(n, R, p));
}
}
// This code is contributed by divyeshrabadiya07
JavaScript
<script>
// Javascript program to answer queries
// of nCr in O(1) time.
var N = 1000001;
// array to store inverse of 1 to N
factorialNumInverse = Array(N+1).fill(0);
// array to precompute inverse of 1! to N!
naturalNumInverse = Array(N+1).fill(0);
// array to store factorial of first N numbers
fact = Array(N+1).fill(0);
// Function to precompute inverse of numbers
function InverseofNumber(p)
{
naturalNumInverse[0] = naturalNumInverse[1] = 1;
for (var i = 2; i <= N; i++)
naturalNumInverse[i] = (naturalNumInverse[p % i] * (p - parseInt(p / i))) % p;
}
// Function to precompute inverse of factorials
function InverseofFactorial(p)
{
factorialNumInverse[0] = factorialNumInverse[1] = 1;
// precompute inverse of natural numbers
for (var i = 2; i <= N; i++)
factorialNumInverse[i] = ((naturalNumInverse[i] * factorialNumInverse[i - 1])) % p;
}
// Function to calculate factorial of 1 to N
function factorial(p)
{
fact[0] = 1;
// precompute factorials
for (var i = 1; i <= N; i++) {
fact[i] = (fact[i - 1] * i) % p;
}
}
// Function to return nCr % p in O(1) time
function Binomial(N, R, p)
{
// n C r = n!*inverse(r!)*inverse((n-r)!)
var ans = ((((fact[N] * factorialNumInverse[R])% p) * factorialNumInverse[N - R]))% p;
return ans;
}
// Driver Code
// Calling functions to precompute the
// required arrays which will be required
// to answer every query in O(1)
p = 100000007;
InverseofNumber(p);
InverseofFactorial(p);
factorial(p);
// 1st query
N = 15;
R = 4;
document.write(Binomial(N, R, p)+"<br>")
// 2nd query
N = 20;
R = 3;
document.write(Binomial(N, R, p));
// This code is contributed by noob2000.
</script>
Time Complexity: O(N) for precomputing and O(1) for every query.
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem