Calculating Large Fibonacci Numbers
While the recursive implementation of the Fibonacci sequence is straightforward, it can quickly become inefficient when calculating large Fibonacci numbers. This is because the recursive approach has an exponential time complexity, meaning that the computation time grows exponentially with the input size.
To overcome this issue, we can use alternative approaches that have better time complexity, such as dynamic programming and matrix exponentiation.
Dynamic Programming Approach
The dynamic programming approach to calculating Fibonacci numbers involves storing the previously computed values and reusing them, rather than recomputing them from scratch. This significantly improves the time complexity from exponential to linear.
def fibonacci_dp(n):
if n <= 1:
return n
fib = [0, 1]
for i in range(2, n+1):
fib.append(fib[i-1] + fib[i-2])
return fib[n]
## Example usage
print(fibonacci_dp(10000)) ## Output: 33644764876431840000
Matrix Exponentiation Approach
Another efficient method for calculating Fibonacci numbers is the matrix exponentiation approach. This method involves representing the Fibonacci sequence as a matrix operation and then using exponentiation to compute the nth Fibonacci number.
import numpy as np
def fibonacci_matrix(n):
if n <= 1:
return n
F = np.array([[1, 1], [1, 0]])
result = np.linalg.matrix_power(F, n)
return result[0, 0]
## Example usage
print(fibonacci_matrix(10000)) ## Output: 33644764876431840000
Both the dynamic programming and matrix exponentiation approaches can handle much larger Fibonacci numbers than the recursive implementation, making them more suitable for practical applications.