To compute the n-th Fibonacci number in less than (O(n)) time, we can use Matrix Exponentiation or Fast Doubling (also known as the Efficient Doubling Method). Here, I'll explain the Fast Doubling method, which achieves (O(\log n)) time complexity.
Fast Doubling Method (Efficient Doubling)
The Fast Doubling method leverages the following recurrence relations:
These relations allow us to compute (F(n)) and (F(n+1)) simultaneously in a recursive manner, reducing the number of steps required.
Algorithm:
Base Cases:
(F(0) = 0)
(F(1) = 1)
Recursive Step:
If (n) is even, use (F(2n) = F(n)(2F(n+1) - F(n))).
If (n) is odd, use (F(2n+1) = F(n+1)^2 + F(n)^2).
Combine Results:
Compute (F(n)) and (F(n+1)) in a single recursive call.
Pseudocode:
python
def fibonacci(n):
if n == 0:
return (0, 1) # F(n), F(n+1)
else:
a, b = fibonacci(n // 2)
if n % 2 == 0:
return (a * (2 * b - a), b * b + a * a)
else:
return (b * b + a * a, b * (2 * a - b))
return a
# To compute the n-th Fibonacci number:
def fib(n):
if n == 0:
return 0
return fibonacci(n - 1)[0]
Explanation:
The function fibonacci(n) returns a tuple ((F(n), F(n+1))).
For even (n), it computes (F(n)) and (F(n+1)) using the first recurrence relation.
For odd (n), it computes (F(n)) and (F(n+1)) using the second recurrence relation.
The recursion depth is (O(\log n)), as we halve (n) at each step.
Time Complexity:
The time complexity of this algorithm is (O(\log n)), which is significantly better than the (O(n)) time complexity of the naive recursive or iterative approaches.
Example:
For (n = 5):
Compute (F(2)) and (F(3)) using (F(1)) and (F(2)).
Use the results to compute (F(5)).
This method efficiently computes the n-th Fibonacci number in logarithmic time.