⚡️ Speed up function gcd_recursive by 12%
#153
+3
−3
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 12% (0.12x) speedup for
gcd_recursiveinsrc/math/computation.py⏱️ Runtime :
34.1 microseconds→30.3 microseconds(best of492runs)📝 Explanation and details
The optimization converts the recursive Euclidean algorithm to an iterative implementation, eliminating function call overhead. Instead of making recursive calls with
return gcd_recursive(b, a % b), the optimized version uses awhileloop that updates variables in-place witha, b = b, a % b.Key Performance Improvements:
The line profiler results demonstrate this improvement: total execution time dropped from 1.141ms to 0.258ms (77% reduction), with the iterative loop operations being significantly faster per hit (329.3ns vs 3257ns per operation).
Test Case Performance:
The optimization shows consistent improvements across most test cases, with particularly strong gains (25-40% faster) on cases requiring multiple iterations like large numbers, Fibonacci sequences, and deep GCD computations. Simple cases (like GCD with 0) show smaller or no improvements since they terminate immediately, bypassing the recursive overhead advantage.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-gcd_recursive-mhbepnqxand push.