Binomial Coefficient | geeksforgeeks| solution

 Given two integers n and r, find nCr. Since the answer may be very large, calculate the answer modulo 109+7.

Example 1:

Input: n = 3, r = 2
Output: 3
Explaination: 3C2 = 3. 


Example 2:

Input: n = 2, r = 4
Output: 0
Explaination: r is greater than n.


Your Task:
You do not need to take input or print anything. Your task is to complete the function nCr() which takes n and r as input parameters and returns nCmodulo 109+7..


Ans : 


int nCr(int n, int k){

        

        int C[n + 1][k + 1];

    int i, j;

    int mod = 1e9 + 7;

 

    // Calculate value of Binomial Coefficient

    // in bottom up manner

    if(k > n )

    return 0;

    for (i = 0; i <= n; i++) {

        for (j = 0; j <= min(i, k); j++) {

             

             if(j > i)

             C[i][j] = 0;

             else

             if(i == 0)

             C[i][j] = 0;

            // Base Cases

            else

            if (j == 0 || j == i)

                C[i][j] = 1;

 

            // Calculate value using

            // previously stored values

            else

                C[i][j] = ((C[i - 1][j - 1])%mod + (C[i - 1][j])%mod)%mod;

        }

    }

    return C[n][k];

    }



Comments