(Translated by https://www.hiragana.jp/)
Program to calculate the value of nCr Efficiently - GeeksforGeeks
Open In App

Program to calculate the value of nCr Efficiently

Last Updated : 11 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two numbers n, r ( n>=r ). The task is to find the value of C(n, r) for big value of n.

Examples: 

Input: n = 30, r = 15
Output: 155117520
C(30, 15) is 155117520 by  30!/((30-15)!*15!)


Input: n = 50, r = 25
Output: 126410606437752

Approach: A simple code can be created with the following knowledge that : 

C(n, r) = [n * (n-1) * .... * (n-r+1)] / [r * (r-1) * .... * 1]

However, for big values of n, r the products may overflow, hence during each iteration we divide the current variables holding value of products by their gcd. 

Below is the required implementation: 

C++
// C++ implementation to find nCr
#include <bits/stdc++.h>
using namespace std;

// Function to find the nCr
void printNcR(int n, int r)
{

    // p holds the value of n*(n-1)*(n-2)...,
    // k holds the value of r*(r-1)...
    long long p = 1, k = 1;

    // C(n, r) == C(n, n-r),
    // choosing the smaller value
    if (n - r < r)
        r = n - r;

    if (r != 0) {
        while (r) {
            p *= n;
            k *= r;

            // gcd of p, k
            long long m = __gcd(p, k);

            // dividing by gcd, to simplify
            // product division by their gcd 
            // saves from the overflow
            p /= m;
            k /= m;

            n--;
            r--;
        }

        // k should be simplified to 1
        // as C(n, r) is a natural number
        // (denominator should be 1 ) .
    }

    else
        p = 1;

    // if our approach is correct p = ans and k =1
    cout << p << endl;
}

// Driver code
int main()
{
    int n = 50, r = 25;

    printNcR(n, r);

    return 0;
}
Java Python3 C# PHP JavaScript

Output
126410606437752

Time Complexity: O( R Log N) 
Auxiliary Space: O(1), since no extra space has been taken.


Article Tags :

Similar Reads