⚡️ Speed up function gcd_recursive by 15%
#154
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 :
402 microseconds→349 microseconds(best of135runs)📝 Explanation and details
The optimized code replaces recursive function calls with an iterative
whileloop, eliminating Python's function call overhead. This is the key performance improvement.What changed:
gcd_recursive(b, a % b)) to iterative loop (while b: a, b = b, a % b)if b == 0) since the while loop naturally terminates whenbbecomes 0Why it's faster:
return gcd_recursive(b, a % b)) took 15.7% of total time.Performance gains by test case type:
gcd_recursive(12, 18)andgcd_recursive(13, 17)where recursion overhead compoundsgcd_recursive(7, 0)that terminate quickly show less improvement since there's less recursion to eliminateThe algorithm complexity remains O(log min(a,b)) but with significantly lower constant factors due to removing Python's recursive call mechanics.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-gcd_recursive-mhbmk9nxand push.