⚡️ Speed up function gcd_recursive by 15%
#123
Closed
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.
📄 15% (0.15x) speedup for
gcd_recursiveinsrc/math/computation.py⏱️ Runtime :
24.2 microseconds→21.0 microseconds(best of701runs)📝 Explanation and details
The optimization replaces recursion with iteration, converting the recursive GCD implementation into an iterative while loop. This eliminates Python's function call overhead, which is significant due to stack frame creation/destruction and parameter passing on each recursive call.
Key Changes:
if b == 0: return awithwhile b != 0:return gcd_recursive(b, a % b)witha, b = b, a % breturn aafter the loopWhy This Is Faster:
Performance Characteristics:
b=0initially (no loop iterations needed)✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_3vjj4ioc/tmpuucwg31g/test_concolic_coverage.py::test_gcd_recursiveTo edit these changes
git checkout codeflash/optimize-gcd_recursive-mh13gh00and push.