-
Notifications
You must be signed in to change notification settings - Fork 20.2k
Closed
Labels
Description
File: Combinations.java
file under Maths
package
nCk
is calculated as (n!)/((k!)(n - k)!)
- The above method can exceed limit of long when factorial(n) is larger than limits of long variable.
- Thus even if
nCk
is within range of long variable above reason can lead to incorrect result. - Also since it is creating factorial considering all n values, it will be slow.
- This is an optimized version of computing combinations.
- Observations:
nC(k + 1) = (n - k) * nCk / (k + 1)
- We know the value of
nCk
whenk = 1
which isnCk = n
- Using this base value and above formula we can compute the next term
nC(k+1)
Note:
The optimized version will also fail at a point when the input is too big which can't be saved in long.