Given a number n, find the nth Fibonacci number. The Fibonacci sequence is defined such that each number is the sum of the two preceding ones, starting from 0 and 1. Mathematically:
F₀ = 0, F₁ = 1
Fₙ = Fₙ₋₁ + Fₙ₋₂ for n ≥ 2
The sequence begins as: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Example: To calculate the nth fibonacci term we can directly apply the fibonacci formula using recursion. Each call creates two more calls, leading to repeated calculations until we find the targeted term.
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(9))
Output
34
The above approach is not the optimal one, the nth fibonacci term can be calculated more optimally using the following approaches
Optimized Matrix Exponentiation
Matrix Exponentiation represents Fibonacci numbers using a 2×2 matrix. The matrix is repeatedly squared using recursion to reach the required power. This reduces the number of multiplications by dividing the problem into smaller parts.
def multiply(F, M):
x = F[0][0]*M[0][0] + F[0][1]*M[1][0]
y = F[0][0]*M[0][1] + F[0][1]*M[1][1]
z = F[1][0]*M[0][0] + F[1][1]*M[1][0]
w = F[1][0]*M[0][1] + F[1][1]*M[1][1]
F[0][0], F[0][1], F[1][0], F[1][1] = x, y, z, w
def power(F, n):
if n <= 1:
return
M = [[1, 1], [1, 0]]
power(F, n // 2)
multiply(F, F)
if n % 2:
multiply(F, M)
def fib(n):
if n == 0:
return 0
F = [[1, 1], [1, 0]]
power(F, n - 1)
return F[0][0]
print(fib(9))
Output
34
Explanation:
- multiply(F, M) updates matrix values using multiplication formula
- power(F, n) calls itself with n // 2 and squares matrix using multiply(F, F)
- if n % 2 multiplies once more for odd powers
- fib(n) initializes matrix and returns F[0][0]
Dynamic Programming (Space Optimized)
This method computes Fibonacci numbers iteratively by storing only the last two values. Each step updates the pair to move forward in the sequence.
def fibonacci(n):
if n < 0:
return "Incorrect input"
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fibonacci(9))
Output
34
Explanation:
- a, b = 0, 1 stores first two values
- for _ in range(n) runs loop n times
- a, b = b, a + b shifts values to next pair
- return a returns required Fibonacci number
Recursion with Memoization
Memoization method stores previously computed Fibonacci values in a dictionary. When a value is needed again, it is directly returned instead of recalculating.
fib_cache = {0: 0, 1: 1}
def fibonacci(n):
if n in fib_cache:
return fib_cache[n]
fib_cache[n] = fibonacci(n-1) + fibonacci(n-2)
return fib_cache[n]
print(fibonacci(9))
Output
34
Explanation:
- fib_cache stores computed results
- if n in fib_cache returns stored value
- fibonacci(n-1) + fibonacci(n-2) computes new value
- fib_cache[n] = ... saves result for reuse
Please refer complete article on Program for Fibonacci numbers for more details!