Python Program for nth Fibonacci number (original) (raw)

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.

Python `

def fibonacci(n): if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(9))

`

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.

Python `

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))

`

**Explanation:

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.

Python `

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))

`

**Explanation:

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.

Python `

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))

`

**Explanation:

Please refer complete article on Program for Fibonacci numbers for more details!