File tree Expand file tree Collapse file tree
code_to_optimize/java/src/main/java/com/example Expand file tree Collapse file tree Original file line number Diff line number Diff line change 99public 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 /**
You can’t perform that action at this time.
0 commit comments