⚡️ Speed up method Fibonacci.fibonacci by 26%
#1452
+21
−1
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.
📄 26% (0.26x) speedup for
Fibonacci.fibonacciincode_to_optimize/java/src/main/java/com/example/Fibonacci.java⏱️ Runtime :
5.69 milliseconds→4.53 milliseconds(best of8runs)📝 Explanation and details
The optimized code achieves a 25% runtime improvement (from 5.69ms to 4.53ms) by replacing the exponential-time recursive Fibonacci algorithm with a logarithmic-time fast-doubling algorithm.
Key Changes:
Algorithm complexity reduction: The original recursive approach has O(2^n) time complexity due to redundant recalculation of the same Fibonacci values. The optimized version uses the fast-doubling method with O(log n) time complexity, processing each bit of n exactly once.
Iterative bit-traversal approach: Instead of recursive calls, the optimization iterates through the bits of n from most significant to least significant, maintaining two Fibonacci values (a = F(k), b = F(k+1)) and doubling k at each step using the mathematical identities:
Constant space usage: The iterative approach uses only four local variables (a, b, c, d) regardless of input size, eliminating the deep call stack overhead that grows with n in the recursive version.
Why This Is Faster:
Integer.numberOfLeadingZeros, bit shifting) instead of arithmetic comparisonsThe optimization maintains identical behavior including exception handling and correctness across all test cases, making it a pure performance win with no trade-offs.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-Fibonacci.fibonacci-mlhd2cw6and push.