Commit 462f0f5
authored
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
1 file changed
+4
-3
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | | - | |
5 | | - | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
0 commit comments