Skip to content

Commit 79c7e38

Browse files
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)
1 parent 78af0c4 commit 79c7e38

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

maths/combinations.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
"""
22
https://en.wikipedia.org/wiki/Combination
33
"""
4-
from math import factorial
5-
64

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

4043

4144
if __name__ == "__main__":

0 commit comments

Comments
 (0)