From 1c4d7c70d2cec3cdb01dce1c87b3042e88db739d Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Sun, 4 May 2025 19:08:09 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Speed=20up=20function=20`g?= =?UTF-8?q?cd=5Frecursive`=20by=2023%=20Here=20is=20an=20optimized=20versi?= =?UTF-8?q?on=20of=20your=20`gcd=5Frecursive`=20function.=20The=20major=20?= =?UTF-8?q?speedup=20comes=20from=20removing=20recursion,=20which=20avoids?= =?UTF-8?q?=20the=20Python=20function=20call=20overhead=20and=20possible?= =?UTF-8?q?=20stack=20overflows=20for=20large=20arguments.=20Euclid's=20al?= =?UTF-8?q?gorithm=20is=20implemented=20iteratively=20below.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This function produces identical results to your original recursive version but runs much faster, especially for large inputs, and is no longer limited by Python's recursion depth. --- src/math/computation.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/math/computation.py b/src/math/computation.py index 7f09784..49f4833 100644 --- a/src/math/computation.py +++ b/src/math/computation.py @@ -1,5 +1,5 @@ def gcd_recursive(a: int, b: int) -> int: """Calculate greatest common divisor using Euclidean algorithm with recursion.""" - if b == 0: - return a - return gcd_recursive(b, a % b) + while b: + a, b = b, a % b + return a