Skip to content

Commit 462f0f5

Browse files
Optimize gcd_recursive
The optimization replaces recursion with iteration to eliminate function call overhead. The original recursive implementation makes ~27,165 recursive function calls (as shown in the line profiler), each requiring stack frame creation, parameter passing, and return value handling. The iterative version uses a simple `while` loop with tuple assignment to achieve the same mathematical result. **Key changes:** - Replaced recursive calls with `while b:` loop - Used tuple assignment `a, b = b, a % b` for the Euclidean algorithm steps - Eliminated ~27k function call overhead operations **Why it's faster:** - Function calls in Python are expensive due to stack frame management and parameter validation - The iterative approach reduces the profiled execution time from 13.76ms to 4.69ms (65% reduction) - Loop operations are much faster than recursive calls in Python's interpreter **Performance characteristics:** The optimization shows consistent 10-60% speedups across test cases, with the largest gains on cases requiring more iterations (like large coprime numbers showing 50-60% improvement). Simple cases with immediate termination (like `gcd(5, 0)`) show minimal improvement since they avoid most recursive overhead anyway. The optimization is particularly effective for the large-scale tests, showing 23-66% improvements on bulk operations.
1 parent a45e450 commit 462f0f5

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

src/math/computation.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
def gcd_recursive(a: int, b: int) -> int:
22
"""Calculate greatest common divisor using Euclidean algorithm with recursion."""
3-
if b == 0:
4-
return a
5-
return gcd_recursive(b, a % b)
3+
# Use an iterative approach to eliminate recursive call overhead
4+
while b:
5+
a, b = b, a % b
6+
return a

0 commit comments

Comments
 (0)