26. nCr (Combination)
The problem can be found at the following link: Question Link
My Approach
To calculate the combination value (nCr), I have used the following approach:
The simple formula for calculating combinations is
C(n, r) = n! / (r! * (n - r)!)
, which represents the number of ways to chooser
items from a set ofn
items.To optimize the calculation, we determine the maximum value between
(n - r)
andr
and eliminate common factors from the numerator and denominator. In the code,b
representsmax(n-r, r)
anda
representsmin(n-r, r)
.After eliminating common factors, the formula becomes
(n * (n - 1) * (n - 2) * ... * (b + 1)) / (a!)
.To avoid overflow and optimize the calculation further, we perform modulo operations during the intermediate steps.
First, we calculate the modular inverses of
(a * (a - 1) * ... * 1)
using the Extended Euclidean Algorithm and multiply them together using the modulo operation.Finally, we multiply the numerator
(n * (n - 1) * (n - 2) * ... * (b + 1))
with the modular inverses and return the result.
Time and Auxiliary Space Complexity
Time Complexity:
O(n)
, where n is the value ofn
. We need to calculate the factorials and modular inverses for(a!)
and perform multiplication operations.Auxiliary Space Complexity:
O(1)
as we are not using any extra space that scales with the input.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated