Skip to content

Commit 5ce36ed

Browse files
authored
Merge pull request #2022 from codeflash-ai/codeflash/optimize-Fibonacci.fibonacci-mnqq81k5
⚡️ Speed up method `Fibonacci.fibonacci` by 2,036%
2 parents c7125c3 + 4856c84 commit 5ce36ed

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)