VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-to-calculate-the-value-of-ncr-efficiently/

⇱ Program to calculate the value of nCr Efficiently - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program to calculate the value of nCr Efficiently

Last Updated : 11 Jul, 2025

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: 


Output
126410606437752

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

Comment
Article Tags:
Article Tags: