Skip to content

Commit cc5751d

Browse files
In place of calculating the factorial several times we can run a loop k times to calculate the combination
### Describe your change: 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 895dffb commit cc5751d

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

maths/combinations.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
"""
22
https://en.wikipedia.org/wiki/Combination
33
"""
4-
from math import factorial
5-
6-
74
def combinations(n: int, k: int) -> int:
85
"""
96
Returns the number of different combinations of k length which can
@@ -35,8 +32,11 @@ def combinations(n: int, k: int) -> int:
3532
# to calculate a factorial of a negative number, which is not possible
3633
if n < k or k < 0:
3734
raise ValueError("Please enter positive integers for n and k where n >= k")
38-
return factorial(n) // (factorial(k) * factorial(n - k))
39-
35+
res = 1
36+
for i in range(k):
37+
res = res * (n - i)
38+
res = res // (i + 1)
39+
return res
4040

4141
if __name__ == "__main__":
4242
print(

0 commit comments

Comments
 (0)