Skip to content

[Enhancement] Combinations #2618

@kumanoit

Description

@kumanoit

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 when k = 1 which is nCk = 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.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions