26. nCr (Combination)
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
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 choose r
items from a set of n
items.
To optimize the calculation, we determine the maximum value between (n - r)
and r
and eliminate common factors from the numerator and denominator. In the code, b
represents max(n-r, r)
and a
represents min(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 Complexity: O(n)
, where n is the value of n
. 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.
For discussions, questions, or doubts related to this solution, please visit our . 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 repository.