From cc5751dfc819bd39f263f11913cecb9806e32dcd Mon Sep 17 00:00:00 2001 From: SubhranShu2332 <124662904+SubhranShu2332@users.noreply.github.com> Date: Sun, 8 Oct 2023 13:56:06 +0530 Subject: [PATCH 1/2] 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) --- maths/combinations.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/maths/combinations.py b/maths/combinations.py index a2324012c01f..d4c03264fbea 100644 --- a/maths/combinations.py +++ b/maths/combinations.py @@ -1,9 +1,6 @@ """ https://en.wikipedia.org/wiki/Combination """ -from math import factorial - - def combinations(n: int, k: int) -> int: """ Returns the number of different combinations of k length which can @@ -35,8 +32,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 = res * (n - i) + res = res // (i + 1) + return res if __name__ == "__main__": print( From 52c9e4b96b4e4993bff3dbbfc4e63d4cfc67acab Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 8 Oct 2023 08:27:31 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- maths/combinations.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/maths/combinations.py b/maths/combinations.py index d4c03264fbea..f65155801b52 100644 --- a/maths/combinations.py +++ b/maths/combinations.py @@ -1,6 +1,8 @@ """ https://en.wikipedia.org/wiki/Combination """ + + def combinations(n: int, k: int) -> int: """ Returns the number of different combinations of k length which can @@ -38,6 +40,7 @@ def combinations(n: int, k: int) -> int: res = res // (i + 1) return res + if __name__ == "__main__": print( "The number of five-card hands possible from a standard",