mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
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:
parent
982bc27358
commit
e7a59bfff5
|
@ -1,7 +1,6 @@
|
||||||
"""
|
"""
|
||||||
https://en.wikipedia.org/wiki/Combination
|
https://en.wikipedia.org/wiki/Combination
|
||||||
"""
|
"""
|
||||||
from math import factorial
|
|
||||||
|
|
||||||
|
|
||||||
def combinations(n: int, k: int) -> int:
|
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
|
# to calculate a factorial of a negative number, which is not possible
|
||||||
if n < k or k < 0:
|
if n < k or k < 0:
|
||||||
raise ValueError("Please enter positive integers for n and k where n >= k")
|
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__":
|
if __name__ == "__main__":
|
||||||
|
|
Loading…
Reference in New Issue
Block a user