Skip to content

Commit e7a59bf

Browse files
SubhranShu2332pre-commit-ci[bot]tianyizheng02
authored
In place of calculating the factorial several times we can run a loop k times to calculate the combination (TheAlgorithms#10051)
* In place of calculating the factorial several times we can run a loop k times to calculate the combination for example: 5 C 3 = 5! / (3! * (5-3)! ) = (5*4*3*2*1)/[(3*2*1)*(2*1)] =(5*4*3)/(3*2*1) so running a loop k times will reduce the time complexity to O(k) * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update maths/combinations.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Tianyi Zheng <[email protected]>
1 parent 982bc27 commit e7a59bf

File tree

1 file changed

+5
-2
lines changed

1 file changed

+5
-2
lines changed

maths/combinations.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
"""
22
https://en.wikipedia.org/wiki/Combination
33
"""
4-
from math import factorial
54

65

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

4043

4144
if __name__ == "__main__":

0 commit comments

Comments
 (0)