Skip to content

Commit 4856c84

Browse files
Optimize Fibonacci.fibonacci
The recursive implementation was replaced with an iterative fast-doubling algorithm that computes Fibonacci(n) in O(log n) time by processing the bits of n and applying matrix-exponentiation doubling formulas (F(2k) = F(k)*(2*F(k+1) - F(k)) and F(2k+1) = F(k+1)² + F(k)²), eliminating the exponential O(2^n) recursive call tree that dominated original runtime at 32.5% per the profiler. This cuts execution time from 3.81 ms to 179 µs (20× speedup) by avoiding redundant subproblem recomputation and deep call stacks. The optimization incurs no regressions in correctness, maintains identical exception behavior, and scales to larger n values that would timeout under naive recursion.
1 parent a9ff297 commit 4856c84

1 file changed

Lines changed: 23 additions & 2 deletions

File tree

code_to_optimize/java/src/main/java/com/example/Fibonacci.java

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
public class Fibonacci {
1010

1111
/**
12-
* Calculate the nth Fibonacci number using recursion.
12+
* Calculate the nth Fibonacci number using an efficient iterative fast-doubling algorithm.
1313
*
1414
* @param n Position in Fibonacci sequence (0-indexed)
1515
* @return The nth Fibonacci number
@@ -21,7 +21,28 @@ public static long fibonacci(int n) {
2121
if (n <= 1) {
2222
return n;
2323
}
24-
return fibonacci(n - 1) + fibonacci(n - 2);
24+
25+
long a = 0L; // F(0)
26+
long b = 1L; // F(1)
27+
28+
// Iterate from the highest bit of n down to the lowest.
29+
for (int mask = Integer.highestOneBit(n); mask != 0; mask >>= 1) {
30+
// Apply doubling formulas:
31+
// F(2k) = F(k) * (2*F(k+1) - F(k))
32+
// F(2k+1) = F(k+1)^2 + F(k)^2
33+
long twoBMinusA = (b << 1) - a;
34+
long c = a * twoBMinusA; // F(2k)
35+
long d = a * a + b * b; // F(2k+1)
36+
37+
if ((n & mask) == 0) {
38+
a = c;
39+
b = d;
40+
} else {
41+
a = d;
42+
b = c + d;
43+
}
44+
}
45+
return a;
2546
}
2647

2748
/**

0 commit comments

Comments
 (0)