Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions code_to_optimize/java/src/main/java/com/example/Algorithms.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
public class Algorithms {

/**
* Calculate Fibonacci number using recursive approach.
* Calculate Fibonacci number using fast doubling algorithm (O(log n)).
*
* @param n The position in Fibonacci sequence (0-indexed)
* @return The nth Fibonacci number
Expand All @@ -18,7 +18,28 @@ public long fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
// Fast doubling O(log n) computation to reduce time and memory usage.
long a = 0L; // F(0)
long b = 1L; // F(1)

int mask = Integer.highestOneBit(n);
for (; mask != 0; mask >>>= 1) {
// Apply doubling formulas:
// F(2k) = F(k) * (2*F(k+1) - F(k))
// F(2k+1) = F(k+1)^2 + F(k)^2
long twoB = b + b;
long d = a * (twoB - a); // F(2k)
long e = a * a + b * b; // F(2k+1)

if ((n & mask) == 0) {
a = d;
b = e;
} else {
a = e;
b = d + e;
}
}
return a;
}

/**
Expand Down
Loading