pythondef fibonacci(n):
"""Calculate the nth Fibonacci number using matrix
exponentiation."""
F = [[1, 1], [1, 0]]
if n == 0:
return 0
power(F, n - 1)
return F[0][0]
def multiply(F, M):
"""Helper function to multiply Fibonacci matrices."""
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] = x
F[0][1] = y
F[1][0] = z
F[1][1] = w
def power(F, n):
"""Helper function to exponentiate the Fibonacci matrix."""
M = [[1, 1], [1, 0]]
for _ in range(2, n+1):
multiply(F, M)
# Calculate the 100th Fibonacci number.
fibonacci(100)
I apologize for the error. It seems there was a problem with the execution of the code. Let me try a different approach. I'll use the closed-form expression for the nth Fibonacci number, which is known as Binet's formula. This formula can be used to compute Fibonacci numbers directly:
However, for large values of , this formula can suffer from rounding errors due to the finite precision of floating-point arithmetic. As an alternative, we can use an iterative approach to calculate large Fibonacci numbers.
Let's try the iterative approach.
pythondef fibonacci(n):
"""Calculate the nth Fibonacci number iteratively."""
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
# Calculate the 100th Fibonacci number.
fibonacci(100)
The 100th Fibonacci number is 354224848179261915075.