The Wayback Machine - https://web.archive.org/web/20241001092353/https://www.geeksforgeeks.org/introduction-and-dynamic-programming-solution-to-compute-ncrp/
Open In App

Introduction and Dynamic Programming solution to compute nCr%p

Last Updated : 23 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given three numbers n, r and p, compute value of nCr mod p. 
Example: 

Input:  n = 10, r = 2, p = 13
Output: 6
Explanation: 10C2 is 45 and 45 % 13 is 6.

We strongly recommend that you click here and practice it, before moving on to the solution.

METHOD 1: (Using Dynamic Programming)

A Simple Solution is to first compute nCr, then compute nCr % p. This solution works fine when the value of nCr is small. 
What if the value of nCr is large? 
The value of nCr%p is generally needed for large values of n when nCr cannot fit in a variable, and causes overflow. So computing nCr and then using modular operator is not a good idea as there will be overflow even for slightly larger values of n and r. For example the methods discussed here and here cause overflow for n = 50 and r = 40.
The idea is to compute nCr using below formula  

   C(n, r) = C(n-1, r-1) + C(n-1, r)
   C(n, 0) = C(n, n) = 1

Working of Above formula and Pascal Triangle: 
Let us see how above formula works for C(4, 3)
1==========>> n = 0, C(0, 0) = 1 
1–1========>> n = 1, C(1, 0) = 1, C(1, 1) = 1 
1–2–1======>> n = 2, C(2, 0) = 1, C(2, 1) = 2, C(2, 2) = 1 
1–3–3–1====>> n = 3, C(3, 0) = 1, C(3, 1) = 3, C(3, 2) = 3, C(3, 3)=1 
1–4–6–4–1==>> n = 4, C(4, 0) = 1, C(4, 1) = 4, C(4, 2) = 6, C(4, 3)=4, C(4, 4)=1 
So here every loop on i, builds i’th row of pascal triangle, using (i-1)th row
Extension of above formula for modular arithmetic: 
We can use distributive property of modular operator to find nCr % p using above formula.

   C(n, r)%p = [ C(n-1, r-1)%p + C(n-1, r)%p ] % p
   C(n, 0) = C(n, n) = 1

The above formula can be implemented using Dynamic Programming using a 2D array.
The 2D array based dynamic programming solution can be further optimized by constructing one row at a time. See Space optimized version in below post for details.
Binomial Coefficient using Dynamic Programming
Below is implementation based on the space optimized version discussed in above post.  

C++

// A Dynamic Programming based solution to compute nCr % p
#include <bits/stdc++.h>
using namespace std;
 
// Returns nCr % p
int nCrModp(int n, int r, int p)
{
    // Optimization for the cases when r is large
    if (r > n - r)
        r = n - r;
 
    // 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];
}
 
// Driver program
int main()
{
    int n = 10, r = 2, p = 13;
    cout << "Value of nCr % p is " << nCrModp(n, r, p);
    return 0;
}

                    

JAVA

// A Dynamic Programming based
// solution to compute nCr % p
import java.io.*;
import java.util.*;
import java.math.*;
 
class GFG {
 
    // Returns nCr % p
    static int nCrModp(int n, int r, int p)
    {
        if (r > n - r)
            r = n - r;
 
        // 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];
    }
 
    // Driver program
    public static void main(String args[])
    {
        int n = 10, r = 2, p = 13;
        System.out.println("Value of nCr % p is "
                           + nCrModp(n, r, p));
    }
}
 
// This code is contributed by Nikita Tiwari.

                    

Python3

# A Dynamic Programming based solution to compute nCr % p
 
# Returns nCr % p
def nCrModp(n, r, p):
 
    # Optimization for the cases when r is large
    # compared to n-r
    if (r > n- r):
        r = n - r 
 
    # 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 for i in range(r + 1)]
 
    C[0] = 1 # Top row of Pascal Triangle
 
    # 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
        for j in range(min(i, r), 0, -1):
 
            # nCj = (n - 1)Cj + (n - 1)C(j - 1)
            C[j] = (C[j] + C[j-1]) % p
 
    return C[r]
 
# Driver Program
n = 10
r = 2
p = 13
print('Value of nCr % p is', nCrModp(n, r, p))
 
# This code is contributed by Soumen Ghosh

                    

C#

// A Dynamic Programming based
// solution to compute nCr % p
using System;
 
class GFG {
 
    // Returns nCr % p
    static int nCrModp(int n, int r, int p)
    {
 
        // Optimization for the cases when r is large
        if (r > n - r)
            r = n - r;
 
        // 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];
 
        for (int i = 0; i < r + 1; i++)
            C[i] = 0;
 
        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];
    }
 
    // Driver program
    public static void Main()
    {
        int n = 10, r = 2, p = 13;
 
        Console.Write("Value of nCr % p is "
                      + nCrModp(n, r, p));
    }
}
 
// This code is contributed by nitin mittal.

                    

PHP

<?php
// A Dynamic Programming based
// solution to compute nCr % p
     
// Returns nCr % p
function nCrModp($n, $r, $p)
{
 
// Optimization for the cases when r is large
if ($r > $n - $r)
    $r = $n - $r;
 
// 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();
 
for( $i = 0; $i < $r + 1; $i++)
    $C[$i] = 0;
 
// 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--)
 
        // nCj = (n-1)Cj + (n-1)C(j-1);
        $C[$j] = ($C[$j] +
                  $C[$j - 1]) % $p;
}
 
return $C[$r];
}
 
// Driver Code
$n = 10; $r = 2;$p = 13;
 
echo "Value of nCr % p is ",
         nCrModp($n, $r, $p);
 
// This code is contributed
// by anuj_67.
?>

                    

Javascript

<script>
// A Dynamic Programming based
// solution to compute nCr % p
 
// Returns nCr % p
function nCrModp(n,r,p)
{
    if (r > n - r)
            r = n - r;
  
        // The array C is going to store last
        // row of pascal triangle at the end.
        // And last entry of last row is nCr
        let C = new Array(r + 1);
         for(let i = 0; i < r + 1; i++)
            C[i] = 0;
        C[0] = 1; // Top row of Pascal Triangle
  
        // One by constructs remaining rows of Pascal
        // Triangle from top to bottom
        for (let i = 1; i <= n; i++) {
  
            // Fill entries of current row using previous
            // row values
            for (let 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];
}
 
// Driver program
let n = 10, r = 2, p = 13;
document.write("Value of nCr % p is "
                   + nCrModp(n, r, p));
 
// This code is contributed by avanitrachhadiya2155
</script>

                    

Output
Value of nCr % p is 6

Time complexity of above solution is O(n*r) and it requires O(r) space. There are more and better solutions to above problem. 
Compute nCr % p | Set 2 (Lucas Theorem)

METHOD 2(Using Pascal Triangle and Dynamic Pro)

Another approach lies in utilizing the concept of the Pascal Triangle. Instead of calculating the nCr value for every n starting from n=0 till n=n, the approach aims at using the nth row itself for the calculation. The method proceeds by finding out a general relationship between nCr and nCr-1.

FORMULA: C(n,r)=C(n,r-1)* (n-r+1)/r

Example:

For instance, take n=5 and r=3.

Input:  n = 5, r = 3, p = 1000000007
Output: 6
Explanation: 5C3 is 10 and 10 % 100000007 is 10.


As per the formula,
C(5,3)=5!/(3!)*(2!)
C(5,3)=10

Also,
C(5,2)=5!/(2!)*(3!)
C(5,2)=10


Let's try applying the above formula.

C(n,r)=C(n,r-1)* (n-r+1)/r
C(5,3)=C(5,2)*(5-3+1)/3
C(5,3)=C(5,2)*1
C(5,3)=10*1

The above example shows that C(n,r) can be easily calculated by calculating C(n,r-1) and multiplying the result with the term (n-r+1)/r. But this multiplication may cause integer overflow for large values of n. To tackle this situation, use modulo multiplication, and modulo division concepts in order to achieve optimizations in terms of integer overflow.

Let’s find out how to build Pascal Triangle for the same.

{1}\\ {1\hspace{0.1cm} 1}\\ {1\hspace{0.1cm} 2\hspace{0.1cm} 1}\\ {1\hspace{0.1cm} 3\hspace{0.1cm} 3\hspace{0.1cm} 1}\\ {1 \hspace{0.1cm}4\hspace{0.1cm} 6\hspace{0.1cm} 4\hspace{0.1cm} 1}\\ {1\hspace{0.1cm} 5\hspace{0.1cm} 10\hspace{0.1cm} 10\hspace{0.1cm} 5\hspace{0.1cm} 1}

1D array declaration can be further optimized by just the declaration of a single variable to perform calculations. However, integer overflow demands other functions too for the final implementation.

The post below mentions the space and time-optimized implementation for the binary coefficient calculation.

C++

// C++ program to find the nCr%p
// based on optimal Dynamic
// Programming implementation and
// Pascal Triangle concepts
#include <bits/stdc++.h>
using namespace std;
 
// Returns (a * b) % mod
long long moduloMultiplication(long long a, long long b,
                               long long mod)
{
 
    // Initialize result
    long long res = 0;
 
    // Update a if it is more than
    // or equal to mod
    a %= mod;
 
    while (b) {
 
        // If b is odd, add a with result
        if (b & 1)
            res = (res + a) % mod;
 
        // Here we assume that doing 2*a
        // doesn't cause overflow
        a = (2 * a) % mod;
        b >>= 1; // b = b / 2
    }
    return res;
}
 
// C++ function for extended Euclidean Algorithm
long long int gcdExtended(long long int a, long long int b,
                          long long int* x,
                          long long int* y);
 
// Function to find modulo inverse of b. It returns
// -1 when inverse doesn't exists
long long int modInverse(long long int b, long long int m)
{
 
    long long int x, y; // used in extended GCD algorithm
    long long int g = gcdExtended(b, m, &x;, &y;);
 
    // Return -1 if b and m are not co-prime
    if (g != 1)
        return -1;
 
    // m is added to handle negative x
    return (x % m + m) % m;
}
 
// C++ function for extended Euclidean Algorithm (used to
// find modular inverse.
long long int gcdExtended(long long int a, long long int b,
                          long long int* x,
                          long long int* y)
{
 
    // Base Case
    if (a == 0) {
        *x = 0, *y = 1;
        return b;
    }
 
    // To store results of recursive call
    long long int x1, y1;
 
    long long int gcd = gcdExtended(b % a, a, &x1;, &y1;);
 
    // Update x and y using results of recursive
    // call
    *x = y1 - (b / a) * x1;
    *y = x1;
    return gcd;
}
 
// Function to compute a/b under modulo m
long long int modDivide(long long int a, long long int b,
                        long long int m)
{
 
    a = a % m;
    long long int inv = modInverse(b, m);
    if (inv == -1)
        // cout << "Division not defined";
        return 0;
    else
        return (inv * a) % m;
}
 
// Function to calculate nCr % p
int nCr(int n, int r, int p)
{
 
    // Edge Case which is not possible
    if (r > n)
        return 0;
 
    // Optimization for the cases when r is large
    if (r > n - r)
        r = n - r;
 
    // x stores the current result at
    long long int x = 1;
   
    // each iteration
    // Initialized to 1 as nC0 is always 1.
    for (int i = 1; i <= r; i++) {
 
        // Formula derived for calculating result is
        // C(n,r-1)*(n-r+1)/r
        // Function calculates x*(n-i+1) % p.
        x = moduloMultiplication(x, (n + 1 - i), p);
       
        // Function calculates x/i % p.
        x = modDivide(x, i, p);
    }
    return x;
}
 
// Driver Code
int main()
{
 
    long long int n = 5, r = 3, p = 1000000007;
    cout << "Value of nCr % p is " << nCr(n, r, p);
    return 0;
}

                    

Java

// Java program to find the nCr%p
// based on optimal Dynamic
// Programming implementation and
// Pascal Triangle concepts
import java.util.*;
 
class GFG
{
   
    // Returns (a * b) % mod
    static long moduloMultiplication(long a, long b,
                                     long mod)
    {
        // Initialize result
        long res = 0;
 
        // Update a if it is more than
        // or equal to mod
        a %= mod;
 
        while (b > 0) {
 
            // If b is odd, add a with result
            if ((b & 1) != 0)
                res = (res + a) % mod;
 
            // Here we assume that doing 2*a
            // doesn't cause overflow
            a = (2 * a) % mod;
            b >>= 1; // b = b / 2
        }
        return res;
    }
 
    // Global Variables
    static long x, y;
 
    // Function for extended Euclidean Algorithm
    static long gcdExtended(long a, long b)
    {
 
        // Base Case
        if (a == 0) {
            x = 0;
            y = 1;
            return b;
        }
 
        // To store results of recursive call
        long gcd = gcdExtended(b % a, a);
        long x1 = x;
        long y1 = y;
 
        // Update x and y using results of recursive
        // call
        x = y1 - (b / a) * x1;
        y = x1;
 
        return gcd;
    }
 
    static long modInverse(long a, long m)
    {
        long g = gcdExtended(a, m);
 
        // Return -1 if b and m are not co-prime
        if (g != 1)
            return -1;
 
        // m is added to handle negative x
        return (x % m + m) % m;
    }
 
    // Function to compute a/b under modulo m
    static long modDivide(long a, long b, long m)
    {
 
        a = a % m;
        long inv = modInverse(b, m);
        if (inv == -1)
            return 0;
        else
            return (inv * a) % m;
    }
 
    // Function to calculate nCr % p
    static long nCr(long n, long r, long p)
    {
 
        // Edge Case which is not possible
        if (r > n)
            return 0;
 
        // Optimization for the cases when r is large
        if (r > n - r)
            r = n - r;
 
        // x stores the current result at
        long x = 1;
 
        // each iteration
        // Initialized to 1 as nC0 is always 1.
        for (long i = 1L; i <= r; i++) {
 
            // Formula derived for calculating result is
            // C(n,r-1)*(n-r+1)/r
            // Function calculates x*(n-i+1) % p.
            x = moduloMultiplication(x, (n + 1L - i), p);
 
            // Function calculates x/i % p.
            x = modDivide(x, i, p);
        }
        return x;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        long n = 5, r = 3, p = 1000000007;
        System.out.println("Value of nCr % p is "
                           + nCr(n, r, p));
    }
}
 
// This code is contributed by phasing17

                    

Python3

# Python3 program to find the nCr%p
# based on optimal Dynamic
# Programming implementation and
# Pascal Triangle concepts
 
# Returns (a * b) % mod
def moduloMultiplication(a, b, mod):
    # Initialize result
    res = 0
 
    # Update a if it is more than
    # or equal to mod
    a %= mod
 
    while (b):
 
        # If b is odd, add a with result
        if (b & 1):
            res = (res + a) % mod
 
        # Here we assume that doing 2*a
        # doesn't cause overflow
        a = (2 * a) % mod
        b >>= 1    # b = b / 2
 
    return res
 
 
# Global Variables
x, y = 0, 1
 
# Function for extended Euclidean Algorithm
 
 
def gcdExtended(a, b):
    global x, y
 
    # Base Case
    if (a == 0):
 
        x = 0
        y = 1
        return b
 
    # To store results of recursive call
    gcd = gcdExtended(b % a, a)
    x1 = x
    y1 = y
 
    # Update x and y using results of recursive
    # call
    x = y1 - int(b / a) * x1
    y = x1
 
    return gcd
 
 
def modInverse(a, m):
 
    g = gcdExtended(a, m)
 
    # Return -1 if b and m are not co-prime
    if (g != 1):
        return -1
 
    # m is added to handle negative x
    return (x % m + m) % m
 
 
# Function to compute a/b under modulo m
def modDivide(a, b, m):
 
    a = a % m
    inv = modInverse(b, m)
    if (inv == -1):
        return 0
    else:
        return (inv * a) % m
 
 
# Function to calculate nCr % p
def nCr(n, r, p):
 
    # Edge Case which is not possible
    if (r > n):
        return 0
 
    # Optimization for the cases when r is large
    if (r > n - r):
        r = n - r
 
    # x stores the current result at
    x = 1
 
    # each iteration
    # Initialized to 1 as nC0 is always 1.
    for i in range(1, r + 1):
 
        # Formula derived for calculating result is
        # C(n,r-1)*(n-r+1)/r
        # Function calculates x*(n-i+1) % p.
        x = moduloMultiplication(x, (n + 1 - i), p)
 
        # Function calculates x/i % p.
        x = modDivide(x, i, p)
 
    return x
 
# Driver Code
n = 5
r = 3
p = 1000000007
print("Value of nCr % p is ", nCr(n, r, p))
 
# This code is contributed by phasing17

                    

C#

// C# program to find the nCr%p
// based on optimal Dynamic
// Programming implementation and
// Pascal Triangle concepts
using System;
using System.Collections.Generic;
 
class GFG
{
  // Returns (a * b) % mod
  static long moduloMultiplication(long a, long b, long mod)
  {
    // Initialize result
    long res = 0;
 
    // Update a if it is more than
    // or equal to mod
    a %= mod;
 
    while (b > 0) {
 
      // If b is odd, add a with result
      if ((b & 1) != 0)
        res = (res + a) % mod;
 
      // Here we assume that doing 2*a
      // doesn't cause overflow
      a = (2 * a) % mod;
      b >>= 1; // b = b / 2
    }
    return res;
  }
 
  // Global Variables
  static long x, y;
 
  // Function for extended Euclidean Algorithm
  static long gcdExtended(long a, long b){
 
    // Base Case
    if (a == 0)
    {
      x = 0;
      y = 1;
      return b;
    }
 
    // To store results of recursive call  
    long gcd = gcdExtended(b % a, a);
    long x1 = x;
    long y1 = y;
 
    // Update x and y using results of recursive
    // call
    x = y1 - (b / a) * x1;
    y = x1;
 
    return gcd;
  }
 
  static long modInverse(long a, long m)
  {
    long g = gcdExtended(a, m);
 
    // Return -1 if b and m are not co-prime
    if (g != 1)
      return -1;
 
    // m is added to handle negative x
    return (x % m + m) % m;
  }
 
  // Function to compute a/b under modulo m
  static long modDivide(long a, long b, long m)
  {
 
    a = a % m;
    long inv = modInverse(b, m);
    if (inv == -1)
      return 0;
    else
      return (inv * a) % m;
  }
 
  // Function to calculate nCr % p
  static long nCr(long n, long r, long p)
  {
 
    // Edge Case which is not possible
    if (r > n)
      return 0;
 
    // Optimization for the cases when r is large
    if (r > n - r)
      r = n - r;
 
    // x stores the current result at
    long x = 1;
 
    // each iteration
    // Initialized to 1 as nC0 is always 1.
    for (long i = 1L; i <= r; i++) {
 
      // Formula derived for calculating result is
      // C(n,r-1)*(n-r+1)/r
      // Function calculates x*(n-i+1) % p.
      x = moduloMultiplication(x, (n + 1L - i), p);
 
      // Function calculates x/i % p.
      x = modDivide(x, i, p);
    }
    return x;
  }
 
  // Driver Code
  public static void Main(string[] args)
  {
    long n = 5, r = 3, p = 1000000007;
    Console.Write("Value of nCr % p is " + nCr(n, r, p));
  }
}
 
// This code is contributed by phasing17

                    

Javascript

// JavaScript program to find the nCr%p
// based on optimal Dynamic
// Programming implementation and
// Pascal Triangle concepts
 
// Returns (a * b) % mod
function moduloMultiplication(a, b, mod)
{
    // Initialize result
    let res = 0;
 
    // Update a if it is more than
    // or equal to mod
    a %= mod;
 
    while (b) {
 
        // If b is odd, add a with result
        if (b & 1)
            res = (res + a) % mod;
 
        // Here we assume that doing 2*a
        // doesn't cause overflow
        a = (2 * a) % mod;
        b >>= 1; // b = b / 2
    }
    return res;
}
 
// Global Variables
let x, y;
  
// Function for extended Euclidean Algorithm
function gcdExtended(a, b){
       
    // Base Case
    if (a == 0)
    {
        x = 0;
        y = 1;
        return b;
    }
       
    // To store results of recursive call  
    let gcd = gcdExtended(b % a, a);
    let x1 = x;
    let y1 = y;
  
    // Update x and y using results of recursive
    // call
    x = y1 - Math.floor(b / a) * x1;
    y = x1;
   
    return gcd;
}
  
function modInverse(a, m)
{
    let g = gcdExtended(a, m);
     
    // Return -1 if b and m are not co-prime
    if (g != 1)
        return -1;
 
    // m is added to handle negative x
    return (x % m + m) % m;
}
 
// Function to compute a/b under modulo m
function modDivide(a, b, m)
{
 
    a = a % m;
    let inv = modInverse(b, m);
    if (inv == -1)
        return 0;
    else
        return (inv * a) % m;
}
 
// Function to calculate nCr % p
function nCr(n, r, p)
{
 
    // Edge Case which is not possible
    if (r > n)
        return 0;
 
    // Optimization for the cases when r is large
    if (r > n - r)
        r = n - r;
 
    // x stores the current result at
    let x = 1;
   
    // each iteration
    // Initialized to 1 as nC0 is always 1.
    for (var i = 1; i <= r; i++) {
 
        // Formula derived for calculating result is
        // C(n,r-1)*(n-r+1)/r
        // Function calculates x*(n-i+1) % p.
        x = moduloMultiplication(x, (n + 1 - i), p);
       
        // Function calculates x/i % p.
        x = modDivide(x, i, p);
    }
    return x;
}
 
// Driver Code
let n = 5, r = 3, p = 1000000007;
console.log("Value of nCr % p is ", nCr(n, r, p));
 
 
// This code is contributed by phasing17

                    

Output
Value of nCr % p is 10

Complexity Analysis:

  • The above code needs an extra of O(1) space for the calculations.
  • The time involved in the calculation of nCr % p is of the order O(n).

This article is improved by Aryan Gupta.  



Previous Article
Next Article

Similar Reads

Compute nCr % p | Set 4 (Chinese Remainder theorem with Lucas Theorem)
Given three numbers n, r and p, the task is to compute the value of nCr % p. Note: p is a square-free number and the largest prime factor of p ≤ 50. Examples: Input: n = 10, r = 2, p = 13Output: 6Explanation: 10C2 is 45 and 45 % 13= 6 Input: n = 6, r = 2, p = 13Output: 2 Approach: We have already discussed several other approaches of this problem.
10 min read
Compute nCr%p using Lucas Theorem
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 intr
12 min read
Compute nCr%p using Fermat Little Theorem
Given three numbers n, r and p, compute the value of nCr mod p. Here p is a prime number greater than n. Here nCr is Binomial Coefficient.Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6. Input: n = 6, r = 2, p = 13 Output: 2Recommended PracticenCrTry It! We have discussed the following methods in previous po
15+ min read
Vertex Cover Problem (Dynamic Programming Solution for Tree)
A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. The problem to find minimum size vertex cover of a graph is NP complete. But it can be solved in polynomial time for tre
15+ min read
Find initial integral solution of Linear Diophantine equation if finite solution exists
Given three integers a, b, and c representing a linear equation of the form: ax + by = c. The task is to find the initial integral solution of the given equation if a finite solution exists. A Linear Diophantine equation (LDE) is an equation with 2 or more integer unknowns and the integer unknowns are each to at most degree of 1. Linear Diophantine
8 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Introduction to Dynamic Programming on Trees
Dynamic Programming(DP) is a technique to solve problems by breaking them down into overlapping sub-problems which follows the optimal substructure. There are various problems using DP like subset sum, knapsack, coin change etc. DP can also be applied on trees to solve some specific problems.Pre-requisite: DFSGiven a tree with N nodes and N-1 edges
10 min read
Sum of product of r and rth Binomial Coefficient (r * nCr)
Given a positive integer n. The task is to find the sum of the product of r and rth Binomial Coefficient. In other words find: ? (r * nCr), where 0 <= r <= n.Examples: Input : n = 2 Output : 4 0.2C0 + 1.2C1 + 2.2C2 = 0*2 + 1*2 + 2*1 = 4 Input : n = 5 Output : 80 Method 1 (Brute Force) : The idea is to iterate a loop i from 0 to n and evaluate
9 min read
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!/(2
9 min read
Find a pair from the given array with maximum nCr value
Given an array arr[] of n positive integers. The task is to find elements arr[i] and arr[j] from the array such that arr[i]Carr[j] is maximum possible. In case of more than 1 valid pairs, print any one of them.Examples: Input: arr[] = {3, 1, 2} Output: 3 2 3C1 = 3 3C2 = 3 2C1 = 2 (3, 1) and (3, 2) are the only pairs with maximum nCr.Input: arr[] =
14 min read
Find if nCr is divisible by the given prime
Given three integers N, R and P where P is prime, the task is to find whether NCR is divisible by P or not.Examples: Input: N = 6, R = 2, P = 7 Output: No 6C2 = 15 which is not divisible by 7.Input: N = 7, R = 2, P = 3 Output: Yes 7C2 = 21 which is divisible by 3. Approach: We know that NCR = N! / (R! * (N - R)!). Now using Legendre Formula, find t
5 min read
Find a pair (n,r) in an integer array such that value of nCr is maximum
Given an array of non-negative integers arr[]. The task is to find a pair (n, r) such that value of nCr is maximum possible r < n. nCr = n! / (r! * (n - r)!) Examples: Input: arr[] = {5, 2, 3, 4, 1} Output: n = 5 and r = 2 5C3 = 5! / (3! * (5 - 3)!) = 10Input: arr[] = {0, 2, 3, 4, 1, 6, 8, 9} Output: n = 9 and r = 4 Naive approach: A simple appr
7 min read
Program to calculate value of nCr using Recursion
Given two numbers N and r, find the value of NCr using recursion Examples: Input: N = 5, r = 2Output: 10Explanation: The value of 5C2 is 10 Input: N = 3, r = 1Output: 3 Approach 1: One very interesting way to find the C(n,r) is the recursive method which is based on the recursive equation. C(n,r) = C(n-1,r-1) + C(n-1,r) Below is the implementation
5 min read
Sum of binomial coefficients (nCr) in a given range
Given three values, N, L and R, the task is to calculate the sum of binomial coefficients (nCr) for all values of r from L to R. Examples: Input: N = 5, L = 0, R = 3Output: 26Explanation: Sum of 5C0 + 5C1 + 5C2 + 5C3 = 1 + 5 + 10 + 10 = 26. Input: N = 3, L = 3, R = 3Output: 1 Approach(Using factorial function): Solve this problem by straightforward
8 min read
Calculate nCr using Pascal's Triangle
A useful application of Pascal's triangle is the calculation of combinations. The formula to find nCr is n! / r! * (n - r)! which is also the formula for a cell of Pascal's triangle. Pascal's triangle:  Input: n = 5, r = 3Output: 10Explanation:n! / r! * (n - r)! = 5! / 3! * (2!) = 120 / 12 = 10Input: n = 7, r = 2Output: 21Explanation:n! / r! * (n -
11 min read
Program to calculate value of nCr
Given two numbers N and r, The task is to find the value of NCr . Combinations represent the number of ways to choose r elements from a set of n distinct elements, without regard to the order in which they are selected. The formula for calculating combinations is : C(n,r) = n! / r! * (n-r) ! Where : (n!) represents the factorial of n .(r!) represen
15+ min read
Introduction and Approximate Solution for Vertex Cover Problem
A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either 'u' or 'v' is in the vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. Given an undirected graph, the vertex cover problem is to find minimum size vertex cover. The following are some exa
10 min read
Graphical Solution of Linear Programming Problems
Linear programming is the simplest way of optimizing a problem. Through this method, we can formulate a real-world problem into a mathematical model. There are various methods for solving Linear Programming Problems and one of the easiest and most important methods for solving LPP is the graphical method. In Graphical Solution of Linear Programming
13 min read
Comparison among Greedy, Divide and Conquer and Dynamic Programming algorithm
Greedy algorithm, divide and conquer algorithm, and dynamic programming algorithm are three common algorithmic paradigms used to solve problems. Here's a comparison among these algorithms: Approach:Greedy algorithm: Makes locally optimal choices at each step with the hope of finding a global optimum.Divide and conquer algorithm: Breaks down a probl
4 min read
Dynamic Programming vs Divide-and-Conquer
In this article I’m trying to explain the difference/similarities between dynamic programming and divide and conquer approaches based on two examples: binary search and minimum edit distance (Levenshtein distance).The ProblemWhen I started to learn algorithms it was hard for me to understand the main idea of dynamic programming (DP) and how it is d
12 min read
Minimum moves to make M and N equal by repeated addition of divisors except 1 using Dynamic Programming
Given two integers N and M, the task is to calculate the minimum number of moves to change N to M, where In one move it is allowed to add any divisor of the current value of N to N itself except 1. Print "-1" if it is not possible. Example: Input: N = 4, M = 24Output: 5Explanation: The given value of N can be converted into M using the following st
8 min read
Divide and Conquer Optimization in Dynamic Programming
Dynamic programming (DP) is arguably the most important tool in a competitive programmer's repertoire. There are several optimizations in DP that reduce the time complexity of standard DP procedures by a linear factor or more, such as Knuth's optimization, Divide and Conquer optimization, the Convex Hull Trick, etc. They are, of paramount importanc
15+ min read
Bitmasking and Dynamic Programming | Travelling Salesman Problem
In this post, we will be using our knowledge of dynamic programming and Bitmasking technique to solve one of the famous NP-hard problem "Traveling Salesman Problem".Before solving the problem, we assume that the reader has the knowledge of DP and formation of DP transition relationBitmasking in DPTraveling Salesman problem To understand this concep
15+ min read
Difference between Recursion and Dynamic Programming
Recursion and Dynamic programming are two effective methods for solving big problems into smaller, more manageable subproblems. Despite their similarities, they differ in some significant ways. Below is the Difference Between Recursion and Dynamic programming in Tabular format:Features Recursion Dynamic Programming Definition By breaking a difficul
5 min read
Dynamic Programming (DP) and Directed Acyclic Graphs (DAG)
Pre-Requisite:What is Directed Graph? | Directed Graph meaningDynamic Programming (DP) Tutorial with Problems Every Dynamic Programming problem can be represented as a Directed Acyclic Graph(DAG). The nodes of the DAG represent the subproblems and the edges represents the transitions between the subproblems. Table of Content Relationship Between Dy
15+ min read
Difference between Brute Force and Dynamic Programming
Brute Force: It gives a solution to a problem by using the most straightforward method. However, it is typically not a very optimal solution or one that is flexible for future changes, but it gets the job done. The proverbial brute force programming example is trying all optimal solutions for reaching the final answer.Brute force programming tests
6 min read
Print equal sum sets of Array (Partition Problem) using Dynamic Programming
Given an array arr[]. Determine whether it is possible to split the array into two sets such that the sum of elements in both sets is equal. If it is possible, then print both sets. If it is not possible then output -1. Examples : Input : arr = {5, 5, 1, 11} Output : Set 1 = {5, 5, 1}, Set 2 = {11} Sum of both the sets is 11 and equal. Input : arr
13 min read
Maximum sum of nodes in Binary tree such that no two are adjacent | Dynamic Programming
Given a N-ary tree with a value associated with each node, the task is to choose a subset of these nodes such that sum of chosen nodes is maximum under a constraint that no two chosen node in subset should be directly connected that is, if we have taken a node in our sum then we can’t take its any children in consideration and vice versa.Examples:
9 min read
Distinct palindromic sub-strings of the given string using Dynamic Programming
Given a string str of lowercase alphabets, the task is to find all distinct palindromic sub-strings of the given string. Examples: Input: str = "abaaa" Output: 5 Palindromic sub-strings are "a", "aa", "aaa", "aba" and "b" Input: str = "abcd" Output: 4 Approach: The solution to this problem has been discussed here using Manacher’s algorithm. However
8 min read
Longest path in a directed Acyclic graph | Dynamic Programming
Given a directed graph G with N vertices and M edges. The task is to find the length of the longest directed path in Graph.Note: Length of a directed path is the number of edges in it. Examples: Input: N = 4, M = 5 Output: 3 The directed path 1->3->2->4 Input: N = 5, M = 8 Output: 3 Simple Approach: A naive approach is to calculate the len
8 min read