⚡️ Speed up function gcd_recursive by 16%
#124
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.
📄 16% (0.16x) speedup for
gcd_recursiveinsrc/math/computation.py⏱️ Runtime :
341 microseconds→293 microseconds(best of336runs)📝 Explanation and details
The optimization replaces recursion with iteration, eliminating Python's function call overhead which is the primary bottleneck in recursive algorithms.
Key changes:
if b == 0: return a+return gcd_recursive(b, a % b)→while b: a, b = b, a % b+return aWhy it's faster:
Python function calls are expensive due to stack frame creation, parameter passing, and return value handling. The line profiler shows the recursive call consumed 1.991 microseconds (68.1% of total time). The iterative version eliminates this overhead entirely, executing the same mathematical operations in a tight loop.
Performance characteristics:
gcd(9, 0))The 16% overall speedup comes from removing Python's recursive overhead while preserving identical mathematical behavior.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
🔎 Concolic Coverage Tests and Runtime
codeflash_concolic_6ele6a58/tmpq5jp_dbz/test_concolic_coverage.py::test_gcd_recursiveTo edit these changes
git checkout codeflash/optimize-gcd_recursive-mh13vxx8and push.