Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

In place of calculating the factorial several times we can run a loop k times to calculate the combination #10087

Closed
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