Compute nCr%p using Lucas Theorem
Last Updated :
23 Jul, 2025
Given three numbers n, r and p, compute the value of nCr mod p.
Examples:
Input: n = 10, r = 2, p = 13
Output: 6
Explanation: 10C2 is 45 and 45 % 13 is 6.
Input: n = 1000, r = 900, p = 13
Output: 8
We strongly recommend referring below post as a prerequisite of this.
Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
We have introduced overflow problem and discussed Dynamic Programming based solution in above set 1. The time complexity of the DP-based solution is O(n*r) and it required O(n) space. The time taken and extra space become very high for large values of n, especially values close to 109.
In this post, Lucas Theorem-based solution is discussed. The time complexity of this solution is O(p2 * Logp n) and it requires only O(p) space.
Lucas Theorem:
For non-negative integers n and r and a prime p, the following congruence relation holds:
\binom{n}{r}=\prod_{i=0}^{k}\binom{n_i}{r_i}(mod \ p),
where
n=n_kp^k+n_k_-_1p^k^-^1+.....+n_1p+n0,
and
r=r_kp^k+r_k_-_1p^k^-^1+.....+r_1p+r0
Using Lucas Theorem for nCr % p:
Lucas theorem basically suggests that the value of nCr can be computed by multiplying results of niCri where ni and ri are individual same-positioned digits in base p representations of n and r respectively.
The idea is to one by one compute niCri for individual digits ni and ri in base p. We can compute these values DP based solution discussed in previous post. Since these digits are in base p, we would never need more than O(p) space, and time complexity of these individual computations would be bounded by O(p2).
Below is the implementation of the above idea
C++14
// A Lucas Theorem based solution to compute nCr % p
#include<bits/stdc++.h>
using namespace std;
// Returns nCr % p. In this Lucas Theorem based program,
// this function is only called for n < p and r < p.
int nCrModpDP(int n, int r, int p)
{
// The array C is going to store last row of
// pascal triangle at the end. And last entry
// of last row is nCr
int C[r+1];
memset(C, 0, sizeof(C));
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++)
{
// Fill entries of current row using previous
// row values
for (int j = min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j-1])%p;
}
return C[r];
}
// Lucas Theorem based function that returns nCr % p
// This function works like decimal to binary conversion
// recursive function. First we compute last digits of
// n and r in base p, then recur for remaining digits
int nCrModpLucas(int n, int r, int p)
{
// Base case
if (r==0)
return 1;
// Compute last digits of n and r in base p
int ni = n%p, ri = r%p;
// Compute result for last digits computed above, and
// for remaining digits. Multiply the two results and
// compute the result of multiplication in modulo p.
return (nCrModpLucas(n/p, r/p, p) * // Last digits of n and r
nCrModpDP(ni, ri, p)) % p; // Remaining digits
}
// Driver program
int main()
{
int n = 1000, r = 900, p = 13;
cout << "Value of nCr % p is " << nCrModpLucas(n, r, p);
return 0;
}
Java
// A Lucas Theorem based solution to compute nCr % p
class GFG{
// Returns nCr % p. In this Lucas Theorem based program,
// this function is only called for n < p and r < p.
static int nCrModpDP(int n, int r, int p)
{
// The array C is going to store last row of
// pascal triangle at the end. And last entry
// of last row is nCr
int[] C=new int[r+1];
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++)
{
// Fill entries of current row using previous
// row values
for (int j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j-1])%p;
}
return C[r];
}
// Lucas Theorem based function that returns nCr % p
// This function works like decimal to binary conversion
// recursive function. First we compute last digits of
// n and r in base p, then recur for remaining digits
static int nCrModpLucas(int n, int r, int p)
{
// Base case
if (r==0)
return 1;
// Compute last digits of n and r in base p
int ni = n%p;
int ri = r%p;
// Compute result for last digits computed above, and
// for remaining digits. Multiply the two results and
// compute the result of multiplication in modulo p.
return (nCrModpLucas(n/p, r/p, p) * // Last digits of n and r
nCrModpDP(ni, ri, p)) % p; // Remaining digits
}
// Driver program
public static void main(String[] args)
{
int n = 1000, r = 900, p = 13;
System.out.println("Value of nCr % p is "+nCrModpLucas(n, r, p));
}
}
// This code is contributed by mits
Python3
# A Lucas Theorem based solution
# to compute nCr % p
# Returns nCr % p. In this Lucas
# Theorem based program, this
# function is only called for
# n < p and r < p.
def nCrModpDP(n, r, p):
# The array C is going to store
# last row of pascal triangle
# at the end. And last entry
# of last row is nCr
C = [0] * (n + 1);
# Top row of Pascal Triangle
C[0] = 1;
# One by constructs remaining
# rows of Pascal Triangle from
# top to bottom
for i in range(1, (n + 1)):
# Fill entries of current
# row using previous row
# values
j = min(i, r);
while(j > 0):
C[j] = (C[j] + C[j - 1]) % p;
j -= 1;
return C[r];
# Lucas Theorem based function that
# returns nCr % p. This function
# works like decimal to binary
# conversion recursive function.
# First we compute last digits of
# n and r in base p, then recur
# for remaining digits
def nCrModpLucas(n, r, p):
# Base case
if (r == 0):
return 1;
# Compute last digits of n
# and r in base p
ni = int(n % p);
ri = int(r % p);
# Compute result for last digits
# computed above, and for remaining
# digits. Multiply the two results
# and compute the result of
# multiplication in modulo p.
# Last digits of n and r
return (nCrModpLucas(int(n / p), int(r / p), p) *
nCrModpDP(ni, ri, p)) % p; # Remaining digits
# Driver Code
n = 1000;
r = 900;
p = 13;
print("Value of nCr % p is",
nCrModpLucas(n, r, p));
# This code is contributed by mits
C#
// A Lucas Theorem based solution
// to compute nCr % p
using System;
class GFG
{
// Returns nCr % p. In this Lucas
// Theorem based program, this
// function is only called for
// n < p and r < p.
static int nCrModpDP(int n, int r, int p)
{
// The array C is going to store
// last row of pascal triangle
// at the end. And last entry
// of last row is nCr
int[] C = new int[r + 1];
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining
// rows of Pascal Triangle
// from top to bottom
for (int i = 1; i <= n; i++)
{
// Fill entries of current row
// using previous row values
for (int j = Math.Min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
// Lucas Theorem based function that
// returns nCr % p. This function works
// like decimal to binary conversion
// recursive function. First we compute
// last digits of n and r in base p,
// then recur for remaining digits
static int nCrModpLucas(int n, int r, int p)
{
// Base case
if (r == 0)
return 1;
// Compute last digits of n
// and r in base p
int ni = n % p;
int ri = r % p;
// Compute result for last digits
// computed above, and for remaining
// digits. Multiply the two results
// and compute the result of
// multiplication in modulo p.
return (nCrModpLucas(n / p, r / p, p) * // Last digits of n and r
nCrModpDP(ni, ri, p)) % p; // Remaining digits
}
// Driver Code
public static void Main()
{
int n = 1000, r = 900, p = 13;
Console.Write("Value of nCr % p is " +
nCrModpLucas(n, r, p));
}
}
// This code is contributed
// by ChitraNayal
PHP
<?php
// A Lucas Theorem based
// solution to compute
// nCr % p
// Returns nCr % p. In this
// Lucas Theorem based program,
// this function is only called
// for n < p and r < p.
function nCrModpDP($n, $r, $p)
{
// The array C is going to
// store last row of pascal
// triangle at the end. And
// last entry of last row is nCr
$C = array_fill(0, $n + 1,
false);
// Top row of
// Pascal Triangle
$C[0] = 1;
// One by constructs remaining
// rows of Pascal Triangle from
// top to bottom
for ($i = 1; $i <= $n; $i++)
{
// Fill entries of current
// row using previous row
// values
for ($j = min($i, $r);
$j > 0; $j--)
$C[$j] = ($C[$j] +
$C[$j - 1]) % $p;
}
return $C[$r];
}
// Lucas Theorem based function
// that returns nCr % p. This
// function works like decimal
// to binary conversion recursive
// function. First we compute last
// digits of n and r in base p,
// then recur for remaining digits
function nCrModpLucas($n, $r, $p)
{
// Base case
if ($r == 0)
return 1;
// Compute last digits
// of n and r in base p
$ni = $n % $p;
$ri = $r % $p;
// Compute result for last
// digits computed above,
// and for remaining digits.
// Multiply the two results
// and compute the result of
// multiplication in modulo p.
return (nCrModpLucas($n / $p,
$r / $p, $p) * // Last digits of n and r
nCrModpDP($ni, $ri, $p)) % $p; // Remaining digits
}
// Driver Code
$n = 1000; $r = 900; $p = 13;
echo "Value of nCr % p is " ,
nCrModpLucas($n, $r, $p);
// This code is contributed by ajit
?>
JavaScript
<script>
// A Lucas Theorem based solution to compute nCr % p
// Returns nCr % p. In this Lucas Theorem based program,
// this function is only called for n < p and r < p.
function nCrModpDP(n, r, p)
{
// The array C is going to store last row of
// pascal triangle at the end. And last entry
// of last row is nCr
C = Array(r+1).fill(0);
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (var i = 1; i <= n; i++)
{
// Fill entries of current row using previous
// row values
for (var j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j-1])%p;
}
return C[r];
}
// Lucas Theorem based function that returns nCr % p
// This function works like decimal to binary conversion
// recursive function. First we compute last digits of
// n and r in base p, then recur for remaining digits
function nCrModpLucas(n, r, p)
{
// Base case
if (r==0)
return 1;
// Compute last digits of n and r in base p
var ni = n%p, ri = r%p;
// Compute result for last digits computed above, and
// for remaining digits. Multiply the two results and
// compute the result of multiplication in modulo p.
return (nCrModpLucas(parseInt(n/p), parseInt(r/p), p) * // Last digits of n and r
nCrModpDP(ni, ri, p)) % p; // Remaining digits
}
// Driver program
var n = 1000, r = 900, p = 13;
document.write("Value of nCr % p is " + nCrModpLucas(n, r, p));
</script>
OutputValue of nCr % p is 9
Time Complexity: Time complexity of this solution is O(p2 * Logp n). There are O(Logp n) digits in base p representation of n. Each of these digits is smaller than p, therefore, computations for individual digits take O(p2). Note that these computations are done using DP method which takes O(n*r) time.
Auxiliary Space: O(r) as extra space for array C is being used
Alternate Implementation with O(p2 + Logp n) time and O(p2) space:
The idea is to precompute Pascal triangle for size p x p and store it in 2D array. All values needed would now take O(1) time. Therefore overall time complexity becomes O(p2 + Logp 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