Space and time efficient Binomial Coefficient - GeeksforGeeks

17 Jan, 2022
Write a function that 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!) = 6

Input: n = 5 and k = 2
Output: 10
Explanation: 5 C 2 is 5!/(3!*2!) = 20
We have discussed a O(n*k) time and O(k) extra space algorithm in this post. The value of C(n, k) can be calculated in O(k) time and O(1) extra space. 
Solution:
C(n, k) 
= n! / (n-k)! * k!
= [n * (n-1) *....* 1]  / [ ( (n-k) * (n-k-1) * .... * 1) * 
                            ( k * (k-1) * .... * 1 ) ]
After simplifying, we get
C(n, k) 
= [n * (n-1) * .... * (n-k+1)] / [k * (k-1) * .... * 1]

Also, C(n, k) = C(n, n-k)  
// r can be changed to n-r if r > n-r 
Change r to n-r if r is greater than n-r. and create a variable to store the answer.Run a loop from 0 to r-1In every iteration update ans as (ans*(n-i))/(i+1) where i is the loop counter.So the answer will be equal to ((n/1)*((n-1)/2)*...*((n-r+1)/r!) which is equal to nCr.
Change r to n-r if r is greater than n-r. and create a variable to store the answer.
Run a loop from 0 to r-1
In every iteration update ans as (ans*(n-i))/(i+1) where i is the loop counter.
So the answer will be equal to ((n/1)*((n-1)/2)*...*((n-r+1)/r!) which is equal to nCr.
Following implementation uses above formula to calculate C(n, k).  
C++
C
Java
Python3
C#
PHP
Javascript
// Program to calculate C(n, k)#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){    int res = 1;     // Since C(n, k) = C(n, n-k)    if (k > n - k)        k = n - k;     // Calculate value of    // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]    for (int i = 0; i < k; ++i) {        res *= (n - i);        res /= (i + 1);    }     return res;} // Driver Codeint main(){    int n = 8, k = 2;    cout << "Value of C(" << n << ", "         << k << ") is " << binomialCoeff(n, k);    return 0;} // This is code is contributed by rathbhupendra
// Program to calculate C(n, k)#include <stdio.h> // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){    int res = 1;     // Since C(n, k) = C(n, n-k)    if (k > n - k)        k = n - k;     // Calculate value of    // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]    for (int i = 0; i < k; ++i) {        res *= (n - i);        res /= (i + 1);    }     return res;} /* Driver program to test above function*/int main(){    int n = 8, k = 2;    printf(        "Value of C(%d, %d) is %d ",        n, k, binomialCoeff(n, k));    return 0;}
// Program to calculate C(n, k) in javaclass BinomialCoefficient {    // Returns value of Binomial Coefficient C(n, k)    static int binomialCoeff(int n, int k)    {        int res = 1;         // Since C(n, k) = C(n, n-k)        if (k > n - k)            k = n - k;         // Calculate value of        // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]        for (int i = 0; i < k; ++i) {            res *= (n - i);            res /= (i + 1);        }         return res;    }     /* Driver program to test above function*/    public static void main(String[] args)    {        int n = 8;        int k = 2;        System.out.println("Value of C(" + n + ", " + k + ") "                           + "is"                           + " " + binomialCoeff(n, k));    }}// This Code is Contributed by Saket Kumar
# Python program to calculate C(n, k) # Returns value of Binomial Coefficient# C(n, k)def binomialCoefficient(n, k):    # since C(n, k) = C(n, n - k)    if(k > n - k):        k = n - k    # initialize result    res = 1    # Calculate value of    # [n * (n-1) *---* (n-k + 1)] / [k * (k-1) *----* 1]    for i in range(k):        res = res * (n - i)        res = res // (i + 1)    return res # Driver program to test above functionn = 8k = 2res = binomialCoefficient(n, k)print("Value of C(% d, % d) is % d" %(n, k, res)) # This code is contributed by Aditi Sharma
// C# Program to calculate C(n, k)using System; class BinomialCoefficient {     // Returns value of Binomial    // Coefficient C(n, k)    static int binomialCoeff(int n, int k)    {        int res = 1;         // Since C(n, k) = C(n, n-k)        if (k > n - k)            k = n - k;         // Calculate value of [n * ( n - 1) *---* (        // n - k + 1)] / [k * (k - 1) *----* 1]        for (int i = 0; i < k; ++i) {            res *= (n - i);            res /= (i + 1);        }         return res;    }     // Driver Code    public static void Main()    {        int n = 8;        int k = 2;        Console.Write("Value of C(" + n + ", " + k + ") "                      + "is"                      + " " + binomialCoeff(n, k));    }} // This Code is Contributed by// Smitha Dinesh Semwal.
<?php// Program to calculate C(n, k)// Returns value of Binomial// Coefficient C(n, k) function binomialCoeff($n, $k){    $res = 1;     // Since C(n, k) = C(n, n-k)    if ( $k > $n - $k )        $k = $n - $k;     // Calculate value of    // [n * (n-1) *---* (n-k+1)] /    // [k * (k-1) *----* 1]    for ($i = 0; $i < $k; ++$i)    {        $res *= ($n - $i);        $res /= ($i + 1);    }     return $res;}     // Driver Code    $n = 8;    $k = 2;    echo " Value of C ($n, $k) is ",             binomialCoeff($n, $k); // This code is contributed by ajit.?>
<script> // Program to calculate C(n, k) // Returns value of Binomial Coefficient C(n, k)function binomialCoeff(n, k){    let res = 1;     // Since C(n, k) = C(n, n-k)    if (k > n - k)        k = n - k;     // Calculate value of    // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]    for (let i = 0; i < k; ++i) {        res *= (n - i);        res /= (i + 1);    }     return res;}  // Driver Code     let n = 8;    let k = 2;    document.write("Value of C(" + n + ", " + k + ") "                  + "is"                  + " " + binomialCoeff(n, k)); </script>
Output: 
Value of C(8, 2) is 28
Complexity Analysis: 
Time Complexity: O(r). A loop has to be run from 0 to r. So, the time complexity is O(r).
Auxiliary Space: O(1). As no extra space is required.
YouTubeGeeksforGeeks507K subscribersSpace and time efficient Binomial Coefficient | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=d1Mtfs7dWlg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Smitha Dinesh Semwal
jit_t
rathbhupendra
nidhi_biet
andrew1234
souravghosh0416
singhalyash8080
amartyaghoshgfg
binomial coefficient
Dynamic Programming
Mathematical
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Edit Distance | DP-5
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples