The Wayback Machine - https://web.archive.org/web/20240906013457/https://www.geeksforgeeks.org/binomial-coefficient-dp-9/
Open In App

Binomial Coefficient | DP-9

Last Updated : 24 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
nCr
Show Topics
Solve Problem
Medium
14.82%
3.1L

The following are the common definitions of Binomial Coefficients. 

A binomial coefficient C(n, k) can be defined as the coefficient of x^k in the expansion of (1 + x)^n.

A binomial coefficient C(n, k) also gives the number of ways, disregarding order, that k objects can be chosen from among n objects more formally, the number of k-element subsets (or k-combinations) of a n-element set.

The Problem 
Write a function that takes two parameters n and k and returns the value of Binomial Coefficient C(n, k). For example, your function should return 6 for n = 4 and k = 2, and it should return 10 for n = 5 and k = 2.

Recommended Practice

1) Optimal Substructure 
The value of C(n, k) can be recursively calculated using the following standard formula for Binomial Coefficients.  

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

Following is a simple recursive implementation that simply follows the recursive structure mentioned above.  

C++




// A naive recursive C++ implementation
#include <bits/stdc++.h>
using namespace std;
 
// Returns value of Binomial Coefficient C(n, k)
int binomialCoeff(int n, int k)
{
    // Base Cases
    if (k > n)
        return 0;
    if (k == 0 || k == n)
        return 1;
 
    // Recur
    return binomialCoeff(n - 1, k - 1)
           + binomialCoeff(n - 1, k);
}
 
/* Driver code*/
int main()
{
    int n = 5, k = 2;
    cout << "Value of C(" << n << ", " << k << ") is "
         << binomialCoeff(n, k);
    return 0;
}
 
// This is code is contributed by rathbhupendra


C




// A Naive Recursive Implementation
#include <stdio.h>
 
// Returns value of Binomial Coefficient C(n, k)
int binomialCoeff(int n, int k)
{
    // Base Cases
    if (k > n)
        return 0;
    if (k == 0 || k == n)
        return 1;
 
    // Recur
    return binomialCoeff(n - 1, k - 1)
           + binomialCoeff(n - 1, k);
}
 
/* Driver program to test above function*/
int main()
{
    int n = 5, k = 2;
    printf("Value of C(%d, %d) is %d ", n, k,
           binomialCoeff(n, k));
    return 0;
}


Java




// JAVA Code for Dynamic Programming |
// Set 9 (Binomial Coefficient)
import java.util.*;
 
class GFG {
 
    // Returns value of Binomial
    // Coefficient C(n, k)
    static int binomialCoeff(int n, int k)
    {
 
        // Base Cases
        if (k > n)
            return 0;
        if (k == 0 || k == n)
            return 1;
 
        // Recur
        return binomialCoeff(n - 1, k - 1)
            + binomialCoeff(n - 1, k);
    }
 
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int n = 5, k = 2;
        System.out.printf("Value of C(%d, %d) is %d ", n, k,
                          binomialCoeff(n, k));
    }
}
 
// This code is contributed by Arnav Kr. Mandal.


Python3




# A naive recursive Python implementation
 
 
def binomialCoeff(n, k):
 
    if k > n:
        return 0
    if k == 0 or k == n:
        return 1
 
    # Recursive Call
    return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k)
 
 
# Driver Program to test ht above function
n = 5
k = 2
print ("Value of C(%d,%d) is (%d)" % (n, k,
                                     binomialCoeff(n, k)))
 
# This code is contributed by Nikhil Kumar Singh (nickzuck_007)


C#




// C# Code for Dynamic Programming |
// Set 9 (Binomial Coefficient)
using System;
 
class GFG {
 
    // Returns value of Binomial
    // Coefficient C(n, k)
    static int binomialCoeff(int n, int k)
    {
 
        // Base Cases
        if (k > n)
            return 0;
        if (k == 0 || k == n)
            return 1;
 
        // Recur
        return binomialCoeff(n - 1, k - 1)
            + binomialCoeff(n - 1, k);
    }
 
    /* Driver program to test above function */
    public static void Main()
    {
        int n = 5, k = 2;
        Console.Write("Value of C(" + n + "," + k + ") is "
                      + binomialCoeff(n, k));
    }
}
 
// This code is contributed by Sam007.


Javascript




<script>
// javascript Code for Dynamic Programming |
// Set 9 (Binomial Coefficient)
 
   // Returns value of Binomial
// Coefficient C(n, k)
function binomialCoeff(n , k)
{
 
    // Base Cases
    if (k > n)
        return 0;
    if (k == 0 || k == n)
        return 1;
 
    // Recur
    return binomialCoeff(n - 1, k - 1)
        + binomialCoeff(n - 1, k);
}
 
/* Driver program to test above function */
var n = 5, k = 2;
document.write("Value of C("+n+", "+k+") is "+binomialCoeff(n, k));
 
// This code is contributed by Amit Katiyar
</script>


PHP




<?php
// PHP Code for Dynamic Programming |
// Set 9 (Binomial Coefficient)
 
// Returns value of
// Binomial Coefficient C(n, k)
function binomialCoeff($n, $k)
{
    // Base Cases
    if ($k > $n)
        return 0;
    if ($k==0 || $k==$n)
        return 1;
     
    // Recur
    return binomialCoeff($n - 1, $k - 1) +
               binomialCoeff($n - 1, $k);
}
 
    // Driver Code
    $n = 5;
    $k = 2;
    echo "Value of C","(",$n ,$k,") is "
               , binomialCoeff($n, $k);
 
// This code is contributed by aj_36
?>


Output

Value of C(5, 2) is 10

Time Complexity: O(n*max(k,n-k)) 

Auxiliary Space: O(n*max(k,n-k))

2) Overlapping Subproblems 
It should be noted that the above function computes the same subproblems again and again. See the following recursion tree for n = 5 and k = 2. The function C(3, 1) is called two times. For large values of n, there will be many common subproblems. 
 

Binomial Coefficients Recursion tree

Binomial Coefficients Recursion tree for C(5,2)

Since the same subproblems are called again, this problem has the Overlapping Subproblems property. So the Binomial Coefficient problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, re-computations of the same subproblems can be avoided by constructing a temporary 2D-array C[][] in a bottom-up manner. Following is Dynamic Programming-based implementation. 

C++




// A Dynamic Programming based solution that uses
// table C[][] to calculate the Binomial Coefficient
#include <bits/stdc++.h>
using namespace std;
 
// Prototype of a utility function that
// returns minimum of two integers
int min(int a, int b);
 
// Returns value of Binomial Coefficient C(n, k)
int binomialCoeff(int n, int k)
{
    int C[n + 1][k + 1];
    int i, j;
 
    // Calculate value of Binomial Coefficient
    // in bottom up manner
    for (i = 0; i <= n; i++) {
        for (j = 0; j <= min(i, k); j++) {
            // Base Cases
            if (j == 0 || j == i)
                C[i][j] = 1;
 
            // Calculate value using previously
            // stored values
            else
                C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
        }
    }
 
    return C[n][k];
}
 
// A utility function to return
// minimum of two integers
int min(int a, int b) { return (a < b) ? a : b; }
 
// Driver Code
int main()
{
    int n = 5, k = 2;
    cout << "Value of C[" << n << "][" << k << "] is "
         << binomialCoeff(n, k);
}
 
// This code is contributed by Shivi_Aggarwal


C




// A Dynamic Programming based solution
// that uses table C[][] to
// calculate the Binomial Coefficient
#include <stdio.h>
 
// Prototype of a utility function that
// returns minimum of two integers
int min(int a, int b);
 
// Returns value of Binomial Coefficient C(n, k)
int binomialCoeff(int n, int k)
{
    int C[n + 1][k + 1];
    int i, j;
 
    // Calculate value of Binomial Coefficient
    // in bottom up manner
    for (i = 0; i <= n; i++) {
        for (j = 0; j <= min(i, k); j++) {
            // Base Cases
            if (j == 0 || j == i)
                C[i][j] = 1;
 
            // Calculate value using
            // previously stored values
            else
                C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
        }
    }
 
    return C[n][k];
}
 
// A utility function to return
// minimum of two integers
int min(int a, int b) { return (a < b) ? a : b; }
 
/* Driver program to test above function*/
int main()
{
    int n = 5, k = 2;
    printf("Value of C(%d, %d) is %d ", n, k,
           binomialCoeff(n, k));
    return 0;
}


Java




// A Dynamic Programming based
// solution that uses table C[][] to
// calculate the Binomial Coefficient
 
class BinomialCoefficient {
    // Returns value of Binomial
    // Coefficient C(n, k)
    static int binomialCoeff(int n, int k)
    {
        int C[][] = new int[n + 1][k + 1];
        int i, j;
 
        // Calculate  value of Binomial
        // Coefficient in bottom up manner
        for (i = 0; i <= n; i++) {
            for (j = 0; j <= min(i, k); j++) {
                // Base Cases
                if (j == 0 || j == i)
                    C[i][j] = 1;
 
                // Calculate value using
                // previously stored values
                else
                    C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
            }
        }
 
        return C[n][k];
    }
 
    // A utility function to return
    // minimum of two integers
    static int min(int a, int b) { return (a < b) ? a : b; }
 
    /* Driver program to test above function*/
    public static void main(String args[])
    {
        int n = 5, k = 2;
        System.out.println("Value of C(" + n + "," + k
                           + ") is " + binomialCoeff(n, k));
    }
}
/*This code is contributed by Rajat Mishra*/


Python3




# A Dynamic Programming based Python
# Program that uses table C[][]
# to calculate the Binomial Coefficient
 
# Returns value of Binomial Coefficient C(n, k)
 
 
def binomialCoef(n, k):
    C = [[0 for x in range(k+1)] for x in range(n+1)]
 
    # Calculate value of Binomial
    # Coefficient in bottom up manner
    for i in range(n+1):
        for j in range(min(i, k)+1):
            # Base Cases
            if j == 0 or j == i:
                C[i][j] = 1
 
            # Calculate value using
            # previously stored values
            else:
                C[i][j] = C[i-1][j-1] + C[i-1][j]
 
    return C[n][k]
 
 
# Driver program to test above function
n = 5
k = 2
print("Value of C[" + str(n) + "][" + str(k) + "] is "
      + str(binomialCoef(n, k)))
 
# This code is contributed by Bhavya Jain


C#




// A Dynamic Programming based solution that
// uses table C[][] to calculate the Binomial
// Coefficient
using System;
 
class GFG {
 
    // Returns value of Binomial Coefficient
    // C(n, k)
    static int binomialCoeff(int n, int k)
    {
        int[, ] C = new int[n + 1, k + 1];
        int i, j;
 
        // Calculate value of Binomial
        // Coefficient in bottom up manner
        for (i = 0; i <= n; i++) {
            for (j = 0; j <= Math.Min(i, k); j++) {
                // Base Cases
                if (j == 0 || j == i)
                    C[i, j] = 1;
 
                // Calculate value using previously
                // stored values
                else
                    C[i, j] = C[i - 1, j - 1] + C[i - 1, j];
            }
        }
 
        return C[n, k];
    }
 
    // A utility function to return minimum
    // of two integers
    static int min(int a, int b) { return (a < b) ? a : b; }
 
    /* Driver program to test above function*/
    public static void Main()
    {
        int n = 5, k = 2;
        Console.WriteLine("Value of C(" + n + "," + k
                          + ") is " + binomialCoeff(n, k));
    }
}
 
// This code is contributed by anuj_67.


Javascript




<script>
 
// A Dynamic Programming based
// solution that uses table C to
// calculate the Binomial Coefficient
 
// Returns value of Binomial
// Coefficient C(n, k)
function binomialCoeff(n, k)
{
    var C = Array(n + 1).fill(0).map(
      x => Array(k + 1).fill(0));;
    var i, j;
 
    // Calculate  value of Binomial
    // Coefficient in bottom up manner
    for(i = 0; i <= n; i++)
    {
        for(j = 0; j <= min(i, k); j++)
        {
             
            // Base Cases
            if (j == 0 || j == i)
                C[i][j] = 1;
 
            // Calculate value using
            // previously stored values
            else
                C[i][j] = C[i - 1][j - 1] +
                          C[i - 1][j];
        }
    }
    return C[n][k];
}
 
// A utility function to return
// minimum of two integers
function min(a, b)
{
    return (a < b) ? a : b;
}
 
// Driver code
var n = 5, k = 2;
document.write("Value of C(" + n + "," + k +
                     ") is " + binomialCoeff(n, k));
 
// This code is contributed by 29AjayKumar
 
</script>


PHP




<?php
// A Dynamic Programming based
// solution that uses table C[][] to
// calculate the Binomial Coefficient
 
// Returns value of Binomial
// Coefficient C(n, k)
function binomialCoeff( $n, $k)
{
    $C = array(array());
    $i; $j;
 
    // Calculate value of Binomial
    // Coefficient in bottom up manner
    for ($i = 0; $i <= $n; $i++)
    {
        for ($j = 0; $j <= min($i, $k); $j++)
        {
             
            // Base Cases
            if ($j == 0 || $j == $i)
                $C[$i][$j] = 1;
 
            // Calculate value using
            // previously stored values
            else
                $C[$i][$j] = $C[$i - 1][$j - 1] +
                                 $C[$i - 1][$j];
        }
    }
 
    return $C[$n][$k];
}
 
    // Driver Code
    $n = 5;
    $k = 2;
    echo "Value of C(" ,$n," ",$k, ") is"," "
                 , binomialCoeff($n, $k) ;
 
// This code is contributed by anuj_67.
?>


Output

Value of C[5][2] is 10

Time Complexity: O(n*k) 
Auxiliary Space: O(n*k)

Following is a space-optimized version of the above code. The following code only uses O(k). Thanks to AK for suggesting this method. 

C++




// C++ program for space optimized Dynamic Programming
// Solution of Binomial Coefficient
#include <bits/stdc++.h>
using namespace std;
 
int binomialCoeff(int n, int k)
{
    int C[k + 1];
    memset(C, 0, sizeof(C));
 
    C[0] = 1; // nC0 is 1
 
    for (int i = 1; i <= n; i++)
    {
       
        // Compute next row of pascal triangle using
        // the previous row
        for (int j = min(i, k); j > 0; j--)
            C[j] = C[j] + C[j - 1];
    }
    return C[k];
}
 
/* Driver code*/
int main()
{
    int n = 5, k = 2;
    cout << "Value of C(" << n << "," << k << ")"<< "is " <<binomialCoeff(n, k);
    return 0;
}
 
// This code is contributed by shivanisinghss2110


C




// C program for space optimized Dynamic Programming
// Solution of Binomial Coefficient
#include <stdio.h>
 
int binomialCoeff(int n, int k)
{
    int C[k + 1];
    memset(C, 0, sizeof(C));
 
    C[0] = 1; // nC0 is 1
 
    for (int i = 1; i <= n; i++) {
        // Compute next row of pascal triangle using
        // the previous row
        for (int j = min(i, k); j > 0; j--)
            C[j] = C[j] + C[j - 1];
    }
    return C[k];
}
 
/* Driver code*/
int main()
{
    int n = 5, k = 2;
    printf("Value of C(%d, %d) is %d ", n, k,
           binomialCoeff(n, k));
    return 0;
}


Java




// JAVA Code for Dynamic Programming |
// Set 9 (Binomial Coefficient)
import java.util.*;
 
class GFG {
 
    static int binomialCoeff(int n, int k)
    {
        int C[] = new int[k + 1];
 
        // nC0 is 1
        C[0] = 1;
 
        for (int i = 1; i <= n; i++) {
            // Compute next row of pascal
            // triangle using the previous row
            for (int j = Math.min(i, k); j > 0; j--)
                C[j] = C[j] + C[j - 1];
        }
        return C[k];
    }
 
    /* Driver code  */
    public static void main(String[] args)
    {
        int n = 5, k = 2;
        System.out.printf("Value of C(%d, %d) is %d ", n, k,
                          binomialCoeff(n, k));
    }
}


Python3




# Python program for Optimized
# Dynamic Programming solution to
# Binomial Coefficient. This one
# uses the concept of pascal
# Triangle and less memory
 
 
def binomialCoeff(n, k):
 
    # Declaring an empty array
    C = [0 for i in range(k+1)]
    C[0] = 1  # since nC0 is 1
 
    for i in range(1, n+1):
 
        # Compute next row of pascal triangle using
        # the previous row
        j = min(i, k)
        while (j > 0):
            C[j] = C[j] + C[j-1]
            j -= 1
 
    return C[k]
 
 
# Driver Code
n = 5
k = 2
print ("Value of C(%d,%d) is %d" % (n, k, binomialCoeff(n, k)))
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


C#




// C# Code for Dynamic Programming |
// Set 9 (Binomial Coefficient)
using System;
 
class GFG {
 
    static int binomialCoeff(int n, int k)
    {
        int[] C = new int[k + 1];
 
        // nC0 is 1
        C[0] = 1;
 
        for (int i = 1; i <= n; i++) {
            // Compute next row of pascal
            // triangle using the previous
            // row
            for (int j = Math.Min(i, k); j > 0; j--)
                C[j] = C[j] + C[j - 1];
        }
        return C[k];
    }
 
    /* Driver Code */
    public static void Main()
    {
        int n = 5, k = 2;
        Console.WriteLine("Value of C(" + n + " " + k
                          + ") is " + binomialCoeff(n, k));
    }
}
 
// This code is contributed by anuj_67.


Javascript




<script>
 
// Javascript program for space optimized
// Dynamic Programming
// Solution of Binomial Coefficient
function binomialCoeff(n, k)
{
    let C = new Array(k + 1);
    C.fill(0);
 
    // nC0 is 1
    C[0] = 1;
 
    for(let i = 1; i <= n; i++)
    {
         
        // Compute next row of pascal
        // triangle using the previous
        // row
        for(let j = Math.min(i, k); j > 0; j--)
            C[j] = C[j] + C[j - 1];
    }
    return C[k];
}
 
// Driver code
let n = 5, k = 2;
document.write("Value of C(" + n + " " +
               k + ") is " + binomialCoeff(n, k));
                
// This code is contributed by divyesh072019
 
</script>


PHP




<?php
// PHP program for space optimized
// Dynamic Programming Solution of
// Binomial Coefficient
function binomialCoeff($n, $k)
{
    $C = array_fill(0, $k + 1, 0);
 
    $C[0] = 1; // nC0 is 1
 
    for ($i = 1; $i <= $n; $i++)
    {
        // Compute next row of pascal
        // triangle using the previous row
        for ($j = min($i, $k); $j > 0; $j--)
            $C[$j] = $C[$j] + $C[$j - 1];
    }
    return $C[$k];
}
 
// Driver Code
$n = 5; $k = 2;
echo "Value of C[$n, $k] is ".
        binomialCoeff($n, $k);
     
// This code is contributed by mits.
?>


Output

Value of C(5, 2) is 10 

Time Complexity: O(n*k) 
Auxiliary Space: O(k)

Explanation: 
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
At any time, every element of array C will have some value (ZERO or more) and in the next iteration, the value for those elements comes from the previous iteration. 
In statement, 
C[j] = C[j] + C[j-1] 
The right-hand side represents the value coming from the previous iteration (A row of Pascal’s triangle depends on the previous row). The left-Hand side represents the value of the current iteration which will be obtained by this statement. 

Let's say we want to calculate C(4, 3), 
i.e. n=4, k=3:
All elements of array C of size 4 (k+1) are
initialized to ZERO.
i.e. C[0] = C[1] = C[2] = C[3] = C[4] = 0;
Then C[0] is set to 1
For i = 1:
C[1] = C[1] + C[0] = 0 + 1 = 1 ==>> C(1,1) = 1
For i = 2:
C[2] = C[2] + C[1] = 0 + 1 = 1 ==>> C(2,2) = 1
C[1] = C[1] + C[0] = 1 + 1 = 2 ==>> C(2,1) = 2
For i=3:
C[3] = C[3] + C[2] = 0 + 1 = 1 ==>> C(3,3) = 1
C[2] = C[2] + C[1] = 1 + 2 = 3 ==>> C(3,2) = 3
C[1] = C[1] + C[0] = 2 + 1 = 3 ==>> C(3,1) = 3
For i=4:
C[4] = C[4] + C[3] = 0 + 1 = 1 ==>> C(4,4) = 1
C[3] = C[3] + C[2] = 1 + 3 = 4 ==>> C(4,3) = 4
C[2] = C[2] + C[1] = 3 + 3 = 6 ==>> C(4,2) = 6
C[1] = C[1] + C[0] = 3 + 1 = 4 ==>> C(4,1) = 4
C(4,3) = 4 is would be the answer in our example.

Memoization Approach: The idea is to create a lookup table and follow the recursive top-down approach. Before computing any value, we check if it is already in the lookup table. If yes, we return the value. Else we compute the value and store it in the lookup table. Following is the Top-down approach of dynamic programming to finding the value of the Binomial Coefficient. 

C++




// A Dynamic Programming based
// solution that uses
// table dp[][] to calculate
// the Binomial Coefficient
// A naive recursive approach
// with table C++ implementation
#include <bits/stdc++.h>
using namespace std;
 
// Returns value of Binomial Coefficient C(n, k)
int binomialCoeffUtil(int n, int k, int** dp)
{
    // If value in lookup table then return
    if (dp[n][k] != -1) //    
        return dp[n][k];
 
    // store value in a table before return
    if (k == 0) {
        dp[n][k] = 1;
        return dp[n][k];
    }
     
    // store value in table before return
    if (k == n) {
        dp[n][k] = 1;
        return dp[n][k];
    }
     
    // save value in lookup table before return
    dp[n][k] = binomialCoeffUtil(n - 1, k - 1, dp) +
               binomialCoeffUtil(n - 1, k, dp);
    return dp[n][k];
}
 
int binomialCoeff(int n, int k)
{
    int** dp; // make a temporary lookup table
    dp = new int*[n + 1];
 
    // loop to create table dynamically
    for (int i = 0; i < (n + 1); i++) {
        dp[i] = new int[k + 1];
    }
 
    // nested loop to initialise the table with -1
    for (int i = 0; i < (n + 1); i++) {
        for (int j = 0; j < (k + 1); j++) {
            dp[i][j] = -1;
        }
    }
 
    return binomialCoeffUtil(n, k, dp);
}
 
/* Driver code*/
int main()
{
    int n = 5, k = 2;
    cout << "Value of C(" << n << ", " << k << ") is "
         << binomialCoeff(n, k) << endl;
    return 0;
}
 
// This is code is contributed by MOHAMMAD MUDASSIR


Java




// A Dynamic Programming based
// solution that uses
// table dp[][] to calculate
// the Binomial Coefficient
// A naive recursive approach
// with table Java implementation
import java.util.*;
class GFG{
 
// Returns value of Binomial
// Coefficient C(n, k)
static int binomialCoeffUtil(int n, int k,
                             Vector<Integer> []dp)
{
  // If value in lookup table
  // then return
  if (dp[n].get(k) != -1)    
    return dp[n].get(k);
 
  // store value in a table
  // before return
  if (k == 0)
  {
    dp[n].add(k, 1);
    return dp[n].get(k);
  }
 
  // store value in table
  // before return
  if (k == n)
  {
    dp[n].add(k, 1);
    return dp[n].get(k);
  }
 
  // save value in lookup table
  // before return
  dp[n].add(k, binomialCoeffUtil(n - 1,
                                 k - 1, dp) +
               binomialCoeffUtil(n - 1,
                                 k, dp));
  return dp[n].get(k);
}
 
static int binomialCoeff(int n, int k)
{
  // Make a temporary lookup table
  Vector<Integer> []dp = new Vector[n+1];
 
  // Loop to create table dynamically
  for (int i = 0; i < (n + 1); i++)
  {
    dp[i] = new Vector<Integer>();
    for(int j = 0; j <= k; j++)
      dp[i].add(-1);
  }
  return binomialCoeffUtil(n, k, dp);
}
 
// Driver code
public static void main(String[] args)
{
  int n = 5, k = 2;
  System.out.print("Value of C(" + n +
                   ", " + k + ") is " +
                   binomialCoeff(n, k) + "\n");
}
}
 
// This code is contributed by Rajput-Ji


Python3




# A Dynamic Programming based solution
# that uses table dp[][] to calculate
# the Binomial Coefficient. A naive
# recursive approach with table
# Python3 implementation
 
# Returns value of Binomial
# Coefficient C(n, k)
def binomialCoeffUtil(n, k, dp):
     
    # If value in lookup table then return
    if dp[n][k] != -1:
        return dp[n][k]
 
    # Store value in a table before return
    if k == 0:
        dp[n][k] = 1
        return dp[n][k]
     
    # Store value in table before return
    if k == n:
        dp[n][k] = 1
        return dp[n][k]
     
    # Save value in lookup table before return
    dp[n][k] = (binomialCoeffUtil(n - 1, k - 1, dp) +
                binomialCoeffUtil(n - 1, k, dp))
                 
    return dp[n][k]
 
def binomialCoeff(n, k):
     
    # Make a temporary lookup table
    dp = [ [ -1 for y in range(k + 1) ]
                for x in range(n + 1) ]
 
    return binomialCoeffUtil(n, k, dp)
 
# Driver code
n = 5
k = 2
 
print("Value of C(" + str(n) +
               ", " + str(k) + ") is",
               binomialCoeff(n, k))
 
# This is code is contributed by Prateek Gupta


C#




// C# program for the
// above approach
 
// A Dynamic Programming based
// solution that uses
// table [,]dp to calculate
// the Binomial Coefficient
// A naive recursive approach
// with table C# implementation
using System;
using System.Collections.Generic;
class GFG{
 
// Returns value of Binomial
// Coefficient C(n, k)
static int binomialCoeffUtil(int n, int k,
                             List<int> []dp)
{
  // If value in lookup table
  // then return
  if (dp[n][k] != -1)    
    return dp[n][k];
 
  // store value in a table
  // before return
  if (k == 0)
  {
    dp[n][k] = 1;
    return dp[n][k];
  }
 
  // store value in table
  // before return
  if (k == n)
  {
    dp[n][k] = 1;
    return dp[n][k];
  }
 
  // save value in lookup table
  // before return
  dp[n][k] = binomialCoeffUtil(n - 1,
                               k - 1, dp) +
             binomialCoeffUtil(n - 1,
                               k, dp);
  return dp[n][k];
}
 
static int binomialCoeff(int n, int k)
{
  // Make a temporary lookup table
  List<int> []dp = new List<int>[n + 1];
 
  // Loop to create table dynamically
  for (int i = 0; i < (n + 1); i++)
  {
    dp[i] = new List<int>();
 
    for(int j = 0; j <= k; j++)
      dp[i].Add(-1);
  }
  return binomialCoeffUtil(n, k, dp);
}
 
// Driver code
public static void Main(String[] args)
{
  int n = 5, k = 2;
  Console.Write("Value of C(" + n +
                ", " + k + ") is " +
                binomialCoeff(n, k) + "\n");
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// A Dynamic Programming based solution that
// uses table dp[][] to calculate the
// Binomial Coefficient. A naive recursive
// approach with table Javascript implementation
 
// Returns value of Binomial
// Coefficient C(n, k)
function binomialCoeffUtil(n, k, dp)
{
     
    // If value in lookup table
    // then return
    if (dp[n][k] != -1)   
        return dp[n][k];
     
    // Store value in a table
    // before return
    if (k == 0)
    {
        dp[n][k] = 1;
        return dp[n][k];
    }
     
    // Store value in table
    // before return
    if (k == n)
    {
        dp[n][k] = 1;
        return dp[n][k];
    }
     
    // Save value in lookup table
    // before return
    dp[n][k] = binomialCoeffUtil(n - 1,
                                 k - 1, dp) +
               binomialCoeffUtil(n - 1,
                                 k, dp);
    return dp[n][k];
}
 
function binomialCoeff(n, k)
{
     
    // Make a temporary lookup table
    let dp = new Array(n + 1);
     
    // Loop to create table dynamically
    for(let i = 0; i < (n + 1); i++)
    {
        dp[i] = [];
        for(let j = 0; j <= k; j++)
            dp[i].push(-1);
    }
    return binomialCoeffUtil(n, k, dp);
}
 
// Driver code
let n = 5, k = 2;
document.write("Value of C(" + n +
               ", " + k + ") is " +
               binomialCoeff(n, k) + "\n");
 
// This code is contributed by avanitrachhadiya2155
 
</script>


 Time Complexity: O(n*k)

Auxiliary Space: O(n*k)

Output

Value of C(5, 2) is 10

Cancellation of factors between numerator and denominator:

nCr = (n-r+1)*(n-r+2)*….*n / (r!)

Create an array arr of numbers from n-r+1 to n which will be of size r. As nCr is always an integer, all numbers in the denominator should cancel with the product of the numerator (represented by arr).

for i = 1 to i = r,

        search arr, if arr[j] and i have gcd>1, divide both by the gcd and when i becomes 1, stop the search

Now, the answer is just the product of arr, whose value mod 10^9+7 can be found using a single pass and the formula use (a*b)%mod = (a%mod * b%mod)%mod 

C++




// C++ program to find gcd of
// two numbers in O(log(min(a,b)))
 
#include <bits/stdc++.h>
using namespace std;
 
int gcd(int a, int b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
int nCr(int n, int r)
{
    // base case
    if (r > n)
        return 0;
 
    // C(n,r) = C(n,n-r)
    if (r > n - r)
        r = n - r;
 
    int mod = 1000000007;
 
    // array of elements from n-r+1 to n
    int arr[r];
 
    for (int i = n - r + 1; i <= n; i++) {
        arr[i + r - n - 1] = i;
    }
 
    long int ans = 1;
    // for numbers from 1 to r find arr[j],
    // such that gcd(i,arr[j])>1
    for (int k = 1; k < r + 1; k++) {
        int j = 0, i = k;
        while (j < r) {
            int x = gcd(i, arr[j]);
            if (x > 1) {
                // if gcd>1, divide both by gcd
                arr[j] /= x;
                i /= x;
            }
 
            // if i becomes 1, no need to search arr
            if (i == 1)
                break;
            j += 1;
        }
    }
 
    // single pass to multiply the numerator
    for (int i : arr)
        ans = (ans * i) % mod;
    return (int)ans;
}
 
int main()
{
    int n = 5, r = 2;
    cout << "Value of C(" << n << ", " << r << ") is "
         << nCr(n, r) << "\n";
    return 0;
}
 
// This code is contributed by rajsanghavi9.


Java




import java.util.*;
class GFG
{
    static int gcd(int a, int b) // function to find gcd of two numbers in O(log(min(a,b)))
    {
        if(b==0) return a;
        return gcd(b,a%b);
    }
    static int nCr(int n, int r)
    {
        if(r>n) // base case
            return 0;
        if(r>n-r) // C(n,r) = C(n,n-r) better time complexity for lesser r value
            r = n-r;
        int mod = 1000000007;
        int[] arr = new int[r]; // array of elements from n-r+1 to n
        for(int i=n-r+1; i<=n; i++)
        {
            arr[i+r-n-1] = i;
        }
        long ans = 1;
        for(int k=1;k<r+1;k++) // for numbers from 1 to r find arr[j] such that gcd(i,arr[j])>1
        {
            int j=0, i=k;
            while(j<arr.length)
            {
                int x = gcd(i,arr[j]);
                if(x>1)
                {
                    arr[j] /= x; // if gcd>1, divide both by gcd
                    i /= x;
                }
                if(i==1)
                    break; // if i becomes 1, no need to search arr
                j += 1;
            }
        }
        for(int i : arr) // single pass to multiply the numerator
            ans = (ans*i)%mod;
        return (int)ans;
    }
    // Driver code
    public static void main(String[] args)
    {
        int n = 5, r = 2;
        System.out.print("Value of C(" +  n+ ", " +  r+ ") is "
             +nCr(n, r) +"\n");
    }
}
// This code is contributed by Gautam Wadhwani


Python3




import math
class GFG:
    def nCr(self, n, r):
        def gcd(a,b): # function to find gcd of two numbers in O(log(min(a,b)))
            if b==0: # base case
                return a
            return gcd(b,a%b)
        if r>n:
            return 0
        if r>n-r: # C(n,r) = C(n,n-r) better time complexity for lesser r value
            r = n-r
        mod = 10**9 + 7
        arr = list(range(n-r+1,n+1)) # array of elements from n-r+1 to n
        ans = 1
        for i in range(1,r+1): # for numbers from 1 to r find arr[j] such that gcd(i,arr[j])>1
            j=0
            while j<len(arr):
                x = gcd(i,arr[j])
                if x>1:
                    arr[j] //= x # if gcd>1, divide both by gcd
                    i //= x
                if arr[j]==1: # if element becomes 1, its of no use anymore so delete from arr
                    del arr[j]
                    j -= 1
                if i==1:
                    break # if i becomes 1, no need to search arr
                j += 1
        for i in arr: # single pass to multiply the numerator
            ans = (ans*i)%mod
        return ans
     # Driver code
n = 5
k = 2
ob = GFG()
print("Value of C(" + str(n) +
               ", " + str(k) + ") is",
               ob.nCr(n, k))
  
# This is code is contributed by Gautam Wadhwani


C#




using System;
 
class GFG{
 
// Function to find gcd of two numbers
// in O(log(min(a,b)))  
static int gcd(int a, int b)
{
    if (b == 0)
        return a;
         
    return gcd(b, a % b);
}
 
static int nCr(int n, int r)
{
     
    // Base case
    if (r > n)
        return 0;
         
    // C(n,r) = C(n,n-r) better time
    // complexity for lesser r value
    if (r > n - r)
        r = n - r;
         
    int mod = 1000000007;
     
    // Array of elements from n-r+1 to n
    int[] arr = new int[r];
    for(int i = n - r + 1; i <= n; i++)
    {
        arr[i + r - n - 1] = i;
    }
    long ans = 1;
     
    // For numbers from 1 to r find arr[j]
    // such that gcd(i,arr[j])>1
    for(int k = 1; k < r + 1; k++)
    {
        int j = 0, i = k;
        while (j < arr.Length)
        {
            int x = gcd(i,arr[j]);
            if (x > 1)
            {
                 
                // If gcd>1, divide both by gcd
                arr[j] /= x;
                i /= x;
            }
             
            if (i == 1)
             
                // If i becomes 1, no need
                // to search arr
                break;
                 
            j += 1;
        }
    }
     
    // Single pass to multiply the numerator
    foreach(int i in arr)
        ans = (ans * i) % mod;
         
    return (int)ans;
}
 
// Driver code
static public void Main()
{
    int n = 5, r = 2;
    Console.WriteLine("Value of C(" +  n +
                      ", " +  r + ") is " +
                      nCr(n, r) + "\n");
}
}
 
// This code is contributed by rag2127


Javascript




<script>
 
// Javascript program to find gcd of
// two numbers in O(log(min(a,b)))
function gcd(a, b)
{
    if (b == 0)
        return a;
         
    return gcd(b, a % b);
}
 
function nCr(n, r)
{
     
    // Base case
    if (r > n)
        return 0;
     
    // C(n,r) = C(n,n-r) better time
    // complexity for lesser r value
    if (r > n - r)
        r = n - r;
         
     mod = 1000000007;
      
    // Array of elements from n-r+1 to n
    var arr = new Array(r);
    for(var i = n - r + 1; i <= n; i++)
    {
        arr[i + r - n - 1] = i;
    }
    var ans = 1;
     
    // For numbers from 1 to r find arr[j]
    // such that gcd(i,arr[j])>1
    for(var k = 1; k < r + 1 ; k++)
    {
        var j = 0, i = k;
        while (j < arr.length)
        {
            var x = gcd(i, arr[j]);
            if (x > 1)
            {
                 
                // If gcd>1, divide both by gcd
                arr[j] /= x;
                i /= x;
            }
             
            // If i becomes 1, no need to search arr
            if (i == 1)
                break;
                 
            j += 1;
        }
    }
     
    // Single pass to multiply the numerator
    arr.forEach(function (i)
    {
        ans = (ans * i) % mod;
    });
     
    return ans;
}
 
// Driver code
var n = 5, r = 2;
document.write("Value of C(" + n + ", " +
               r + ") is " + nCr(n, r) + "\n");
 
// This code is contributed by shivanisinghss2110
 
</script>


Output

Value of C(5, 2) is 10

Time Complexity: O(( min(r, n-r)^2 ) * log(n)),   useful when n >> r  or  n >> (n-r)

Auxiliary Space: O(min(r, n-r))

See this for GCD in logarithmic time

Prime factorization of every number from 1 to n using Sieve of Eratosthenes :

1. Create an array SPF of size n+1 to the smallest prime factor of each number from 1 to n 

Set SPF[i] = i for all i = 1 to i = n

2. Use Sieve of Eratosthenes:

for i = 2 to i = n:
if i is prime,
for all multiples j of i, j<=n:
if SPF[j] equals j, set SPF[j] = i

3. Once, we know the SPF of each number from 1 to n, we can find the prime factorization of any number from 1 to n in O(log(n)) time using recursive division by SPF until the number becomes 1

Now, nCr  =  (n-r+1)*(r+2)* ... *(n) / (r)!

4. Create a dictionary (or hashmap) to store the frequency of each prime in the prime factorization of the actual value of nCr.

5. So, just calculate the frequency of each prime in nCr and multiply them raised to the power of their frequency.

6. For the numerator, iterate through i = n-r+1 to i = n, and for all prime factors of i, store their frequency in a dictionary.

( prime_pow[prime_factor] += freq_in_i ) 

7. For the denominator, iterate through i = 1 to i = r and now subtract the frequency instead of adding.

8. Now, traverse the dictionary and multiply the answer to (prime ^ prime_pow[prime]) % (10^9 + 7)

ans = (ans * pow(prime, prime_pow[prime], mod) ) % mod 

C++




#include <bits/stdc++.h>
using namespace std;
 
// pow(base,exp,mod) is used to find
// (base^exp)%mod fast -> O(log(exp))
long int pow(long int b, long int exp, long int mod)
{
    long int ret = 1;
 
    while (exp > 0) {
        if ((exp & 1) > 0)
            ret = (ret * b) % mod;
        b = (b * b) % mod;
        exp >>= 1;
    }
 
    return ret;
}
 
int nCr(int n, int r)
{
    // base case
    if (r > n)
        return 0;
 
    // C(n,r) = C(n,n-r) Complexity for
    // this code is lesser for lower n-r
    if (n - r > r)
        r = n - r;
 
    // list to smallest prime factor
    // of each number from 1 to n
    int SPF[n + 1];
 
    // set smallest prime factor of each
    // number as itself
    for (int i = 1; i <= n; i++)
        SPF[i] = i;
 
    // set smallest prime factor of all
    // even numbers as 2
    for (int i = 4; i <= n; i += 2)
        SPF[i] = 2;
 
    for (int i = 3; i * i < n + 1; i += 2) {
 
        // Check if i is prime
        if (SPF[i] == i) {
            // All multiples of i are
            // composite (and divisible by
            // i) so add i to their prime
            // factorization getpow(j,i)
            // times
            for (int j = i * i; j < n + 1; j += i)
                if (SPF[j] == j) {
                    SPF[j] = i;
                }
        }
    }
    // Hash Map to store power of
    // each prime in C(n,r)
    map<int, int> prime_pow;
 
    // For numerator count frequency of each prime factor
    for (int i = r + 1; i < n + 1; i++) {
 
        int t = i;
 
        // Recursive division to find
        // prime factorization of i
        while (t > 1) {
            if (!prime_pow[SPF[t]]) {
                prime_pow[SPF[t]] = 1;
            }
            else
                prime_pow[SPF[t]]++;
            // prime_pow.put(SPF[t],
            // prime_pow.getOrDefault(SPF[t], 0)
            // + 1);
            t /= SPF[t];
        }
    }
 
    // For denominator subtract the power of
    // each prime factor
    for (int i = 1; i < n - r + 1; i++) {
        int t = i;
 
        // Recursive division to find
        // prime factorization of i
        while (t > 1) {
            prime_pow[SPF[t]]--;
            // prime_pow.put(SPF[t],
            // prime_pow.get(SPF[t]) - 1);
            t /= SPF[t];
        }
    }
 
    // long because mod is large and a%mod
    // * b%mod can overflow int
    long int ans = 1, mod = 1000000007;
 
    // use (a*b)%mod = (a%mod * b%mod)%mod
    for (auto it : prime_pow)
 
        // pow(base,exp,mod) is used to
        // find (base^exp)%mod fast
        ans = (ans
               * pow(it.first, prime_pow[it.first], mod))
              % mod;
    return (int)ans;
}
 
int main()
{
    int n = 5, r = 2;
    cout << "Value of C(" << n << ", " << r << ") is "
         << nCr(n, r) << "\n";
    return 0;
}
 
// This code is contributed by rajsanghavi9.


Java




import java.util.*;
class GFG {
   
    // pow(base,exp,mod) is used to find
    // (base^exp)%mod fast -> O(log(exp))
    static long pow(long b, long exp, long mod)
    {
        long ret = 1;
        while (exp > 0) {
            if ((exp & 1) > 0)
                ret = (ret * b) % mod;
            b = (b * b) % mod;
            exp >>= 1;
        }
        return ret;
    }
    static int nCr(int n, int r)
    {
        if (r > n) // base case
            return 0;
       
        // C(n,r) = C(n,n-r) Complexity for
        // this code is lesser for lower n-r
        if (n - r > r)
            r = n - r;
       
        // list to smallest prime factor
        // of each number from 1 to n
        int[] SPF = new int[n + 1];
       
        // set smallest prime factor of each
        // number as itself
        for (int i = 1; i <= n; i++)
            SPF[i] = i;
       
        // set smallest prime factor of all
        // even numbers as 2
        for (int i = 4; i <= n; i += 2)
            SPF[i] = 2;
       
        for (int i = 3; i * i < n + 1; i += 2)
        {
             
            // Check if i is prime
            if (SPF[i] == i)
            {
               
                // All multiples of i are
                // composite (and divisible by
                // i) so add i to their prime
                // factorization getpow(j,i)
                // times
                for (int j = i * i; j < n + 1; j += i)
                    if (SPF[j] == j) {
                        SPF[j] = i;
                    }
            }
        }
       
       // Hash Map to store power of
       // each prime in C(n,r)
       Map<Integer, Integer> prime_pow
            = new HashMap<>();
       
        // For numerator count frequency of each prime factor
        for (int i = r + 1; i < n + 1; i++)
        {
            int t = i;
             
            // Recursive division to find
            // prime factorization of i
            while (t > 1)
            {
                prime_pow.put(SPF[t],
                    prime_pow.getOrDefault(SPF[t], 0) + 1);
                t /= SPF[t];
            }
        }
       
        // For denominator subtract the power of
        // each prime factor
        for (int i = 1; i < n - r + 1; i++)
        {
            int t = i;
           
            // Recursive division to find
            // prime factorization of i
            while (t > 1)
            {
                prime_pow.put(SPF[t],
                              prime_pow.get(SPF[t]) - 1);
                t /= SPF[t];
            }
        }
       
        // long because mod is large and a%mod
        // * b%mod can overflow int
        long ans = 1, mod = 1000000007;
       
        // use (a*b)%mod = (a%mod * b%mod)%mod
        for (int i : prime_pow.keySet())
           
            // pow(base,exp,mod) is used to
            // find (base^exp)%mod fast
            ans = (ans * pow(i, prime_pow.get(i), mod))
                  % mod;
        return (int)ans;
    }
   
    // Driver code
    public static void main(String[] args)
    {
        int n = 5, r = 2;
        System.out.print("Value of C(" + n + ", " + r
                         + ") is " + nCr(n, r) + "\n");
    }
}
// This code is contributed by Gautam Wadhwani


Python3




# Python code for the above approach
import math
 
class GFG:
    def nCr(self, n, r):
       
        # Base case
        if r > n: 
            return 0
           
        # C(n,r) = C(n,n-r) Complexity for this
        # code is lesser for lower n-r
        if n - r > r: 
            r = n - r
             
        # List to store smallest prime factor
        # of every number from 1 to n
        SPF = [i for i in range(n+1)]
        for i in range(4, n+1, 2):
           
            # set smallest prime factor of
            # all even numbers as 2
            SPF[i] = 2
     
        for i in range(3, n+1, 2): 
         
            if i*i > n:
                break
               
            # Check if i is prime
            if SPF[i] == i: 
                 
                # All multiples of i are composite
                # (and divisible by i) so add i to
                # their prime factorization getpow(j,i) times
                for j in range(i*i, n+1, i):
                    if SPF[j] == j:
                       
                        # set smallest prime factor
                        # of j to i only if it is
                        # not previously set
                        SPF[j] = i
         
         # dictionary to store power of each prime in C(n,r)
        prime_pow = {} 
         
        # For numerator count frequency
        # of each prime factor
        for i in range(r+1, n+1):
            t = i
             
            # Recursive division to
            # find prime factorization of i
            while t > 1:
                if not SPF[t] in prime_pow:
                    prime_pow[SPF[t]] = 1
                else:
                    prime_pow[SPF[t]] += 1
                t //= SPF[t]
         
        # For denominator subtract the
        # power of each prime factor
        for i in range(1, n-r+1): 
            t = i
             
            # Recursive division to
            # find prime factorization of i
            while t > 1: 
                prime_pow[SPF[t]] -= 1
                t //= SPF[t]
        ans = 1
        mod = 10**9 + 7
         
         # Use (a*b)%mod = (a%mod * b%mod)%mod
        for i in prime_pow:
           
            # pow(base,exp,mod) is used to
            # find (base^exp)%mod fast
            ans = (ans*pow(i, prime_pow[i], mod)) % mod
        return ans
 
 
# Driver code
n = 5
k = 2
ob = GFG()
print("Value of C(" + str(n) +
      ", " + str(k) + ") is",
      ob.nCr(n, k))
 
# This is code is contributed by Gautam Wadhwani


C#




using System;
using System.Collections.Generic;
 
public class GFG {
 
    // pow(base,exp,mod) is used to find
    // (base^exp)%mod fast -> O(log(exp))
    static long pow(long b, long exp, long mod)
    {
        long ret = 1;
        while (exp > 0) {
            if ((exp & 1) > 0)
                ret = (ret * b) % mod;
            b = (b * b) % mod;
            exp >>= 1;
        }
        return ret;
    }
    static int nCr(int n, int r)
    {
        if (r > n) // base case
            return 0;
 
        // C(n,r) = C(n,n-r) Complexity for
        // this code is lesser for lower n-r
        if (n - r > r)
            r = n - r;
 
        // list to smallest prime factor
        // of each number from 1 to n
        int[] SPF = new int[n + 1];
 
        // set smallest prime factor of each
        // number as itself
        for (int i = 1; i <= n; i++)
            SPF[i] = i;
 
        // set smallest prime factor of all
        // even numbers as 2
        for (int i = 4; i <= n; i += 2)
            SPF[i] = 2;
 
        for (int i = 3; i * i < n + 1; i += 2) {
 
            // Check if i is prime
            if (SPF[i] == i) {
 
                // All multiples of i are
                // composite (and divisible by
                // i) so add i to their prime
                // factorization getpow(j,i)
                // times
                for (int j = i * i; j < n + 1; j += i)
                    if (SPF[j] == j) {
                        SPF[j] = i;
                    }
            }
        }
 
        // Hash Map to store power of
        // each prime in C(n,r)
        Dictionary<int, int> prime_pow
            = new Dictionary<int, int>();
 
        // For numerator count frequency of each prime
        // factor
        for (int i = r + 1; i < n + 1; i++) {
            int t = i;
 
            // Recursive division to find
            // prime factorization of i
            while (t > 1) {
                if (prime_pow.ContainsKey(SPF[t])) {
                    prime_pow[SPF[t]]
                        = prime_pow[SPF[t]] + 1;
                }
                else {
                    prime_pow.Add(SPF[t], 1);
                }
                t /= SPF[t];
            }
        }
 
        // For denominator subtract the power of
        // each prime factor
        for (int i = 1; i < n - r + 1; i++) {
            int t = i;
 
            // Recursive division to find
            // prime factorization of i
            while (t > 1) {
 
                if (prime_pow.ContainsKey(SPF[t])) {
                    prime_pow[SPF[t]]
                        = prime_pow[SPF[t]] - 1;
                }
 
                t /= SPF[t];
            }
        }
 
        // long because mod is large and a%mod
        // * b%mod can overflow int
        long ans = 1, mod = 1000000007;
 
        // use (a*b)%mod = (a%mod * b%mod)%mod
        foreach(int i in prime_pow.Keys)
 
            // pow(base,exp,mod) is used to
            // find (base^exp)%mod fast
            ans
            = (ans * pow(i, prime_pow[i], mod)) % mod;
        return (int)ans;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int n = 5, r = 2;
        Console.Write("Value of C(" + n + ", " + r + ") is "
                      + nCr(n, r) + "\n");
    }
}
 
// This code contributed by gauravrajput1


Javascript




<script>
 
// Javascript program to find gcd of
// two numbers in O(log(min(a,b)))
 
function gcd(a, b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
 
function nCr(n, r)
{
    // base case
    if (r > n)
        return 0;
 
    // C(n,r) = C(n,n-r)
    if (r > n - r)
        r = n - r;
 
    var mod = 1000000007;
 
    // array of elements from n-r+1 to n
    var arr = new Array(r);
 
    for (var i = n - r + 1; i <= n; i++) {
        arr[i + r - n - 1] = i;
    }
 
    var ans = 1;
    // for numbers from 1 to r find arr[j],
    // such that gcd(i,arr[j])>1
    for (var k = 1; k < r + 1; k++) {
        var j = 0;
        var i = k;
        do {
            var x = gcd(i, arr[j]);
            if (x > 1) {
                // if gcd>1, divide both by gcd
                arr[j] /= x;
                i /= x;
            }
 
            // if i becomes 1, no need to search arr
            if (i == 1)
                break;
            j += 1;
        }
        while (j < r);
    }
 
    // single pass to multiply the numerator
     
    arr.forEach(function (i, index) {
          ans = (ans * i) % mod;
    });       
    return ans;
}
 
 
var n = 5;
var r = 2;
document.write("Value of C(" + n + ", " + r + ") is " + nCr(n, r) + "<br>");
 
// This code is contributed by shivani.
 
</script>


Output

Value of C(5, 2) is 10

Time Complexity: O(n*log(n)),  so useful when r->n/2

Auxiliary Space: O(n)

See this for Prime factorization in O(log(n))

Another Approach: (Modular Inversion technique)

1. The general formula of nCr is ( n*(n-1)*(n-2)* … *(n-r+1) ) / (r!). We can directly use this formula to find nCr. But that will overflow out of bound. We need to find nCr mod m so that it doesn’t overflow. We can easily do it with modular arithmetic formula. 

for the  n*(n-1)*(n-2)* ... *(n-r+1) part we can use the formula,
(a*b) mod m = ((a % m) * (b % m)) % m

2. and for the 1/r! part, we need to find the modular inverse of every number from 1 to r. Then use the same formula above with a modular inverse of 1 to r. We can find modular inverse in O(r) time using  the formula, 

inv[1] = 1
inv[i] = ? ?m/i? * inv[m mod i] mod m
To use this formula, m has to be a prime.

In the practice problem, we need to show the answer with modulo 1000000007 which is a prime. 

So, this technique will work.
 

C++




// C++ program for the above approach
#include<bits/stdc++.h>
using namespace std;
 
// Function to find binomial
// coefficient
int binomialCoeff(int n, int r)
{
 
    if (r > n)
        return 0;
    long long int m = 1000000007;
    long long int inv[r + 1] = { 0 };
    inv[0] = 1;
    if(r+1>=2)
    inv[1] = 1;
 
    // Getting the modular inversion
    // for all the numbers
    // from 2 to r with respect to m
    // here m = 1000000007
    for (int i = 2; i <= r; i++) {
        inv[i] = m - (m / i) * inv[m % i] % m;
    }
 
    int ans = 1;
 
    // for 1/(r!) part
    for (int i = 2; i <= r; i++) {
        ans = ((ans % m) * (inv[i] % m)) % m;
    }
 
    // for (n)*(n-1)*(n-2)*...*(n-r+1) part
    for (int i = n; i >= (n - r + 1); i--) {
        ans = ((ans % m) * (i % m)) % m;
    }
    return ans;
}
 
/* Driver code*/
int main()
{
    int n = 5, r = 2;
    cout << "Value of C(" << n << ", " << r << ") is "
         << binomialCoeff(n, r) << endl;
    return 0;
}


Java




// JAVA program for the above approach
import java.util.*;
class GFG
{
 
// Function to find binomial
// coefficient
static int binomialCoeff(int n, int r)
{
 
    if (r > n)
    return 0;
    long  m = 1000000007;
    long  inv[] = new long[r + 1];
    inv[0] = 1;
    if(r+1>=2)
    inv[1] = 1;
 
    // Getting the modular inversion
    // for all the numbers
    // from 2 to r with respect to m
    // here m = 1000000007
    for (int i = 2; i <= r; i++) {
        inv[i] = m - (m / i) * inv[(int) (m % i)] % m;
    }
 
    int ans = 1;
 
    // for 1/(r!) part
    for (int i = 2; i <= r; i++) {
        ans = (int) (((ans % m) * (inv[i] % m)) % m);
    }
 
    // for (n)*(n-1)*(n-2)*...*(n-r+1) part
    for (int i = n; i >= (n - r + 1); i--) {
        ans = (int) (((ans % m) * (i % m)) % m);
    }
    return ans;
}
 
/* Driver code*/
public static void main(String[] args)
{
    int n = 5, r = 2;
    System.out.print("Value of C(" +  n+ ", " +  r+ ") is "
         +binomialCoeff(n, r) +"\n");
}
}
 
// This code contributed by Rajput-Ji


Python3




# Python3 program for the above approach
 
# Function to find binomial
# coefficient
def binomialCoeff(n, r):
     
    if (r > n):
        return 0
         
    m = 1000000007
    inv = [0 for i in range(r + 1)]
    inv[0] = 1
    if(r+1>=2):
        inv[1] = 1
 
    # Getting the modular inversion
    # for all the numbers
    # from 2 to r with respect to m
    # here m = 1000000007
    for i in range(2, r + 1):
        inv[i] = m - (m // i) * inv[m % i] % m
 
    ans = 1
 
    # for 1/(r!) part
    for i in range(2, r + 1):
        ans = ((ans % m) * (inv[i] % m)) % m
 
    # for (n)*(n-1)*(n-2)*...*(n-r+1) part
    for i in range(n, n - r, -1):
        ans = ((ans % m) * (i % m)) % m
         
    return ans
 
# Driver code
n = 5
r = 2
 
print("Value of C(",n , "," , r ,") is ",binomialCoeff(n, r))
 
# This code is contributed by Pushpesh Raj


C#




// C# program for the above approach
using System;
 
public class GFG
{
 
// Function to find binomial
// coefficient
static int binomialCoeff(int n, int r)
{
 
    if (r > n)
    return 0;
    long  m = 1000000007;
    long  []inv = new long[r + 1];
    inv[0] = 1;
    if(r+1>=2)
    inv[1] = 1;
 
    // Getting the modular inversion
    // for all the numbers
    // from 2 to r with respect to m
    // here m = 1000000007
    for (int i = 2; i <= r; i++) {
        inv[i] = m - (m / i) * inv[(int) (m % i)] % m;
    }
 
    int ans = 1;
 
    // for 1/(r!) part
    for (int i = 2; i <= r; i++) {
        ans = (int) (((ans % m) * (inv[i] % m)) % m);
    }
 
    // for (n)*(n-1)*(n-2)*...*(n-r+1) part
    for (int i = n; i >= (n - r + 1); i--) {
        ans = (int) (((ans % m) * (i % m)) % m);
    }
    return ans;
}
 
/* Driver code*/
public static void Main(String[] args)
{
    int n = 5, r = 2;
    Console.Write("Value of C(" +  n+ ", " +  r+ ") is "
         +binomialCoeff(n, r) +"\n");
}
}
 
 
 
// This code is contributed by 29AjayKumar


Javascript




<script>
        // JavaScript Program for the above approach
 
        // Function to find binomial
        // coefficient
        function binomialCoeff(n, r) {
 
            if (r > n)
                return 0;
            let m = 1000000007;
            let inv = new Array(r + 1).fill(0);
            inv[0] = 1;
            if (r + 1 >= 2)
                inv[1] = 1;
 
            // Getting the modular inversion
            // for all the numbers
            // from 2 to r with respect to m
            // here m = 1000000007
            for (let i = 2; i <= r; i++) {
                inv[i] = m - Math.floor(m / i) * inv[m % i] % m;
            }
 
            let ans = 1;
 
            // for 1/(r!) part
            for (let i = 2; i <= r; i++) {
                ans = ((ans % m) * (inv[i] % m)) % m;
            }
 
            // for (n)*(n-1)*(n-2)*...*(n-r+1) part
            for (let i = n; i >= (n - r + 1); i--) {
                ans = ((ans % m) * (i % m)) % m;
            }
            return ans;
        }
 
        /* Driver code*/
        let n = 5, r = 2;
        document.write("Value of C(" + n + ", " + r + ") is "
            + binomialCoeff(n, r) + "<br>");
 
    // This code is contributed by Potta Lokesh
    </script>


Output

Value of C(5, 2) is 10

Time Complexity: O(n+k)

Auxiliary Space: O(k) 

See this for Space and time-efficient Binomial Coefficient 

References: 
http://www.csl.mtu.edu/cs4321/www/Lectures/Lecture%2015%20-%20Dynamic%20Programming%20Binomial%20Coefficients.htm 

https://cp-algorithms.com/algebra/module-inverse.html

 



Previous Article
Next Article

Similar Reads

Maximum binomial coefficient term value
Given a positive integer n. The task is to find the maximum coefficient term in all binomial coefficient. The binomial coefficient series is nC0, nC1, nC2, ...., nCr, ...., nCn-2, nCn-1, nCn the task is to find maximum value of nCr. Examples: Input : n = 4 Output : 6 4C0 = 1 4C1 = 4 4C2 = 6 4C3 = 1 4C4 = 1 So, maximum coefficient value is 6. Input
11 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 &lt;= r &lt;= 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
Central binomial coefficient
Given an integer N, the task is to find the [Tex]N^{th} [/Tex]Central binomial coefficient. The first few Central binomial coefficients for N = 0, 1, 2, 3... are 1, 2, 6, 20, 70, 252, 924, 3432..... Examples: Input: N = 3 Output: 20 Explanation: [Tex]N^{th} [/Tex]Central Binomial Coefficient = [Tex]\binom{2N}{N} [/Tex]= [Tex]\binom{2*3}{3} [/Tex]=
5 min read
Space and time efficient Binomial Coefficient
Here the function takes two parameters n and k and returns the value of Binomial Coefficient C(n, k). Example: Input: n = 4 and k = 2 Output: 6 Explanation: 4 C 2 is 4!/(2!*2!) = 6Input: n = 5 and k = 2 Output: 10 Explanation: 5 C 2 is 5!/(3!*2!) = 10 We have discussed O(n*k) time and O(k) extra space algorithm in this post. The value of C(n, k) ca
6 min read
Program to find correlation coefficient
Given two array elements and we have to find the correlation coefficient between two arrays. The correlation coefficient is an equation that is used to determine the strength of the relation between two variables. The correlation coefficient is sometimes called as cross-correlation coefficient. The correlation coefficient always lies between -1 to
8 min read
Fibonomial coefficient and Fibonomial triangle
Fibonomial Coefficient: In mathematics, the Fibonomial coefficients or Fibonacci-binomial coefficients are defined as[Tex]\binom{n}{k}_f = \frac{F_n F_{n-1}....F_{n-k+1} }{F_k F_{k-1}....F1} = \frac{n_F!}{k_F!(n-k)_F!} [/Tex]where n and k are non-negative integers, 0 ? k ? n, Fj is the j-th Fibonacci number and n!F is the nth Fibonorial, where 0!F,
11 min read
Range and Coefficient of range of Array
Given an array arr of integer elements, the task is to find the range and coefficient of range of the given array where: Range: Difference between the maximum value and the minimum value in the distribution. Coefficient of Range: (Max – Min) / (Max + Min). Examples: Input: arr[] = {15, 16, 10, 9, 6, 7, 17} Output: Range : 11 Coefficient of Range :
7 min read
Coefficient of Range in a Binary Tree
Given a Binary Tree, the task is to find the Coefficient of Range in it.Range is defined as the difference between the maximum and minimum value in a set of data and Coefficient of Range is the relative measure of the dispersion of the range. Suppose the maximum value in a data set is maxVal and minimum value is minVal then the coefficient of range
9 min read
Replace the maximum element in the array by coefficient of range
Given an array arr[] of integer elements, the task is to replace the maximum element in the array by the coefficient of range of the same array. Coefficient of Range: (Max – Min) / (Max + Min) Examples: Input: arr[] = {15, 16, 10, 9, 6, 7, 17} Output: 15 16 10 9 6 7 0.478261 Max = 17, Min = 6 Coefficient of Range = (Max – Min) / (Max + Min) = 11 /
8 min read
Program for Coefficient of variation
Given an array of size n and the task is to find Coefficient of variation . Coefficient of variation is the ratio of standard deviation and mean. The main purpose of coefficient of variation is to find study of quality assurance by measuring the dispersion of the population data of a probability or frequency distribution, or by determining the cont
6 min read
Maximizing Readability-Coefficient for Book Printing
A book publisher collected data on the readability level of his n books. Book publisher can print any book in 1 unit of time. Readability-Coefficient of a book is defined as the time taken to print that book including previous books multiplied by its readability level, i.e. total_time * readability[i], the task is to return the maximum sum of Reada
8 min read
Clustering Coefficient in Graph Theory
In graph theory, a clustering coefficient is a measure of the degree to which nodes in a graph tend to cluster together. Evidence suggests that in most real-world networks, and in particular social networks, nodes tend to create tightly knit groups characterized by a relatively high density of ties; this likelihood tends to be greater than the aver
5 min read
Permutation Coefficient
Permutation refers to the process of arranging all the members of a given set to form a sequence. The number of permutations on a set of n elements is given by n! , where "!" represents factorial.  The Permutation Coefficient represented by P(n, k) is used to represent the number of ways to obtain an ordered subset having k elements from a set of n
15+ min read
Python | Kendall Rank Correlation Coefficient
What is correlation test? The strength of the association between two variables is known as the correlation test. For instance, if we are interested to know whether there is a relationship between the heights of fathers and sons, a correlation coefficient can be calculated to answer this question. For know more about correlation please refer this.M
3 min read
Sum of Binomial coefficients
Given a positive integer n, the task is to find the sum of binomial coefficient i.enC0 + nC1 + nC2 + ....... + nCn-1 + nCnExamples: Input : n = 4 Output : 16 4C0 + 4C1 + 4C2 + 4C3 + 4C4 = 1 + 4 + 6 + 4 + 1 = 16 Input : n = 5 Output : 32 Method 1 (Brute Force): The idea is to evaluate each binomial coefficient term i.e nCr, where 0 &lt;= r &lt;= n a
8 min read
Middle term in the binomial expansion series
Given three integers A, X, and n. The task is to find the middle term in the binomial expansion series. Examples: Input : A = 1, X = 1, n = 6Output : MiddleTerm = 20 Input : A = 2, X = 4, n = 7Output : MiddleTerm1 = 35840, MiddleTerm2 = 71680 Approach (A + X)n = nC0 An X0 + nC1 An-1 X1 + nC2 An-2 X2 + ......... + nCn-1 A1 Xn-1 + nCn A0 Xn Total num
11 min read
Program for Binomial Coefficients table
Given an integer max, print Binomial Coefficients table that prints all binomial coefficients B(m, x) where m and x vary from 0 to maxExample : Input : max = 3 Output : 0 1 1 1 1 2 1 2 1 3 1 3 3 1 The easiest way to explain what binomial coefficients is to say that they count certain ways of grouping items. Specifically, the binomial coefficient B(
6 min read
Find sum of even index binomial coefficients
Given a positive integer n. The task is to find the sum of even indexed binomial coefficient. That is, nC0 + nC2 + nC4 + nC6 + nC8 + ...........Examples : Input : n = 4Output : 8Explanation: 4C0 + 4C2 + 4C4= 1 + 6 + 1= 8 Input : n = 6Output : 32 Method 1: (Brute Force) The idea is to find all the binomial coefficients and find only the sum of even
8 min read
Sum of squares of binomial coefficients
Given a positive integer n. The task is to find the sum of square of Binomial Coefficient i.e nC02 + nC12 + nC22 + nC32 + ......... + nCn-22 + nCn-12 + nCn2 Examples: Input : n = 4 Output : 70 Input : n = 5 Output : 252 Method 1: (Brute Force) The idea is to generate all the terms of binomial coefficient and find the sum of square of each binomial
9 min read
Program to print binomial expansion series
Given three integers, A, X and n, the task is to print terms of below binomial expression series. (A+X)n = nC0AnX0 + nC1An-1X1 + nC2An-2X2 +....+ nCnA0Xn Examples: Input : A = 1, X = 1, n = 5 Output : 1 5 10 10 5 1 Input : A = 1, B = 2, n = 6 Output : 1 12 60 160 240 192 64 Simple Solution : We know that for each value of n there will be (n+1) term
12 min read
Memory representation of Binomial Heap
Prerequisites: Binomial Heap Binomial trees are multi-way trees typically stored in the left-child, right-sibling representation, and each node stores its degree. Binomial heaps are collection of binomial trees stored in ascending order of size. The root list in the heap is a linked list of roots of the Binomial heap. The degree of the nodes of the
2 min read
Sum of all products of the Binomial Coefficients of two numbers up to K
Given three integers N, M and K, the task is to calculate the sum of products of Binomial Coefficients C(N, i) and C(M, K - i), where i ranges between [0, K]. [Tex]\begin{*align} \sum_{i=0}^{k}C(n, i)*C(m, k-i) \label{sum} \end{*align} [/Tex] Examples: Input: N = 2, M = 2, K = 2 Output: 6 Explanation: C(2, 0) * C(2, 2) + C(2, 1) * C(2, 1) + C(2, 2)
8 min read
Count odd and even Binomial Coefficients of N-th power
Given an integer N, the task is to count the number of even and odd binomial coefficients up to Nth power. Examples: Input: N = 4Output:Odd: 2Even: 3Explanation:The binomial coefficients are as follows:4C0 = 1, 4C1 = 4 , 4C2 = 6 , 4C3 = 4 , 4C4 = 1.Therefore, it can be observed that there exists exactly 2 odd and 3 even Binomial Coefficients. Input
9 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
Sum of product of consecutive Binomial Coefficients
Given a positive integer n. The task is to find the sum of product of consecutive binomial coefficient i.e nC0*nC1 + nC1*nC2 + ..... + nCn-1*nCn Examples: Input : n = 3Output : 153C0*3C1 + 3C1*3C2 +3C2*3C3= 1*3 + 3*3 + 3*1= 3 + 9 + 3= 15Input : n = 4Output : 56Method 1: The idea is to find all the binomial coefficients up to nth term and find the s
15 min read
Binomial Random Variables
In this post, we'll discuss Binomial Random Variables.Prerequisite : Random Variables A specific type of discrete random variable that counts how often a particular event occurs in a fixed number of tries or trials. For a variable to be a binomial random variable, ALL of the following conditions must be met: There are a fixed number of trials (a fi
8 min read
Implementation of Binomial Heap | Set - 2 (delete() and decreseKey())
In previous post i.e. Set 1 we have discussed that implements these below functions: insert(H, k): Inserts a key ‘k’ to Binomial Heap ‘H’. This operation first creates a Binomial Heap with single key ‘k’, then calls union on H and the new Binomial heap.getMin(H): A simple way to getMin() is to traverse the list of root of Binomial Trees and return
15+ min read
Implementation of Binomial Heap
In previous article, we have discussed about the concepts related to Binomial heap. Examples Binomial Heap: 12------------10--------------------20 / \ / | \ 15 50 70 50 40 | / | | 30 80 85 65 | 100A Binomial Heap with 13 nodes. It is a collection of 3 Binomial Trees of orders 0, 2 and 3 from left to right. 10--------------------20 / \ / | \ 15 50 7
15+ min read
Binomial Mean and Standard Deviation - Probability | Class 12 Maths
Binomial distribution is the probability distribution of no. of Bernoulli trials i.e. if a Bernoulli trial is performed n times the probability of its success is given by binomial distribution. Keep in mind that each trial is independent of another trial with only two possible outcomes satisfying the same conditions of Bernoulli trials. Consider th
7 min read
Difference between Binary Heap, Binomial Heap and Fibonacci Heap
Binary Heap:A Binary Heap is a Binary Tree with following properties. It’s a complete binary tree i.e., all levels are completely filled except possibly the last level and the last level has all keys as left as possible. This property of Binary Heap makes them suitable to be stored in an array.A Binary Heap is either Min Heap or Max Heap. In a Min
2 min read