Compute nCr % p | Set 2 (Lucas Theorem) - GeeksforGeeks

22 Mar, 2021
Given three numbers n, r and p, compute 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 to refer 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. 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: where and 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 implementation of above idea 
C++
Java
Python3
C#
PHP
Javascript
// 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 digitsint 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 programint main(){    int n = 1000, r = 900, p = 13;    cout << "Value of nCr % p is " << nCrModpLucas(n, r, p);    return 0;}
// 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 digitsstatic int nCrModpLucas(int n, int r, int p){// Base caseif (r==0)    return 1; // Compute last digits of n and r in base pint 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 programpublic 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
# 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 digitsdef 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 Coden = 1000;r = 900;p = 13;print("Value of nCr % p is",       nCrModpLucas(n, r, p)); # This code is contributed by mits
// A Lucas Theorem based solution// to compute nCr % pusing 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 digitsstatic int nCrModpLucas(int n, int r, int p){// Base caseif (r == 0)    return 1; // Compute last digits of n// and r in base pint 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 Codepublic 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// 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 digitsfunction nCrModpLucas($n, $r, $p){     // Base caseif ($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?>
<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 digitsfunction nCrModpLucas(n, r, p){// Base caseif (r==0)    return 1; // Compute last digits of n and r in base pvar 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 programvar n = 1000, r = 900, p = 13;document.write("Value of nCr % p is " + nCrModpLucas(n, r, p));  </script>
Output: 
Value of nCr % p is 8
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.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).This article is contributed by Ruchir Garg. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
jit_t
Mithun Kumar
ukasp
rutvik_56
large-numbers
Modular Arithmetic
Mathematical
Mathematical
Modular Arithmetic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find GCD or HCF of two numbers
Sieve of Eratosthenes
Print all possible combinations of r elements in a given array of size n
Operators in C / C++
The Knight's tour problem | Backtracking-1
Program for factorial of a number
Program for Decimal to Binary Conversion