In place of calculating the factorial several times we can run a loop k times to calculate the combination (#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 <tianyizheng02@gmail.com>
This commit is contained in:
SubhranShu2332 2023-10-09 00:47:02 +05:30 committed by GitHub
parent 982bc27358
commit e7a59bfff5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,7 +1,6 @@
"""
https://en.wikipedia.org/wiki/Combination
"""
from math import factorial
def combinations(n: int, k: int) -> int:
@ -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 *= n - i
res //= i + 1
return res
if __name__ == "__main__":