Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions maths/combinations.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""
https://en.wikipedia.org/wiki/Combination
"""
from math import factorial


def combinations(n: int, k: int) -> int:
Expand Down Expand Up @@ -35,7 +34,11 @@ def combinations(n: int, k: int) -> int:
# to calculate a factorial of a negative number, which is not possible
if n < k or k < 0:
raise ValueError("Please enter positive integers for n and k where n >= k")
return factorial(n) // (factorial(k) * factorial(n - k))
res = 1
for i in range(k):
res = res * (n - i)
res = res // (i + 1)
return res


if __name__ == "__main__":
Expand Down