⚡️ Speed up function gcd_recursive by 54%
#125
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.
📄 54% (0.54x) speedup for
gcd_recursiveinsrc/math/computation.py⏱️ Runtime :
1.17 milliseconds→758 microseconds(best of302runs)📝 Explanation and details
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
whileloop with tuple assignment to achieve the same mathematical result.Key changes:
while b:loopa, b = b, a % bfor the Euclidean algorithm stepsWhy it's faster:
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.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_0fmmmqp5/tmpasqq6_nv/test_concolic_coverage.py::test_gcd_recursiveTo edit these changes
git checkout codeflash/optimize-gcd_recursive-mh140f0qand push.