The Wayback Machine - https://web.archive.org/web/20240707133513/https://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/
Open In App

Space and time efficient Binomial Coefficient

Last Updated : 11 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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!) = 6
Input: 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) can be calculated in O(k) time and O(1) extra space.

Approach:

  1. Change r to n-r if r is greater than n-r. and create a variable to store the answer.
  2. Run a loop from 0 to r-1
  3. In every iteration update ans as (ans*(n-i))/(i+1) where i is the loop counter.
  4. So the answer will be equal to ((n/1)*((n-1)/2)*…*((n-r+1)/r) which is equal to nCr.
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 

Following implementation uses the above formula to calculate C(n, k). 

C++




// 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 Code
int 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


C




// 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;
}


Java




// Program to calculate C(n, k) in java
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 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


Python3




# 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 function 
n = 8
k = 2
res = binomialCoefficient(n, k)
print("Value of C(% d, % d) is % d" %(n, k, res))
  
# This code is contributed by Aditi Sharma


C#




// 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




<?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.
?>


Javascript




<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.

This article is compiled by Aashish Barnwal and reviewed by the GeeksforGeeks team.



Previous Article
Next Article

Similar Reads

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
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
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
Binomial Coefficient | DP-9
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 (
15+ min read
Space efficient iterative method to Fibonacci number
Given a number n, find n-th Fibonacci Number. Note that F0 = 0, F1 = 1, F2 = 2, ..... Examples : Input : n = 5 Output : 5 Input : n = 10 Output : 89 We have discussed below recursive solution in method 4 of Program for Fibonacci numbers. F[2][2] = |1, 1| |1, 0| M[2][2] = |1, 1| |1, 0| F[n][n] = fib(n) | fib(n-1) ------------------ fib(n-1)| fib(n-2
9 min read
Find the closest element in Binary Search Tree | Space Efficient Method
Given a binary search tree and a target node K. The task is to find the node with the minimum absolute difference with given target value K. NOTE: The approach used should have constant extra space consumed O(1). No recursion or stack/queue like containers should be used. Examples: Input: k = 4 Output: 4 Input: k = 18 Output: 17 A simple solution m
10 min read
Reverse a singly Linked List in groups of given size | Set 4 (Space efficient approach)
Given a linked list, write a function to reverse every k node (where k is an input to the function). Examples: Inputs: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL, k = 3Output: 3-&gt;2-&gt;1-&gt;6-&gt;5-&gt;4-&gt;8-&gt;7-&gt;NULL Inputs: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL, k = 5Output: 5-&gt;4-&gt;3-&gt;2-&gt;1-&gt;8-&gt;
9 min read
Various load balancing techniques used in Hash table to ensure efficient access time
Load balancing refers to the process of distributing workloads evenly across multiple servers, nodes, or other resources to ensure optimal resource utilization, maximize output, minimize response time, and avoid overload of any single resource. Load balancing helps to improve the reliability and scalability of applications and systems, as well as r
3 min read
What is the difference between Auxiliary space and Space Complexity?
Space complexity and Auxiliary space are two of the most often confused and interchangeably used terms when talking about the space complexity of a certain algorithm: Auxiliary Space: The extra space that is taken by an algorithm temporarily to finish its workSpace Complexity: Space complexity is the total space taken by the algorithm with respect
4 min read
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
three90RightbarBannerImg