Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #produced by ChatGPT 4 February 2023 in response to the prompt "So in Python give a complete matrix exponentiation solution for finding the nth fibonacci number."
- def fib(n):
- if n == 0:
- return 0
- if n == 1:
- return 1
- def mat_mult(A, B):
- C = [[0, 0], [0, 0]]
- for i in range(2):
- for j in range(2):
- C[i][j] = A[i][0] * B[0][j] + A[i][1] * B[1][j]
- return C
- def mat_pow(A, n):
- if n == 1:
- return A
- if n % 2 == 0:
- B = mat_pow(A, n//2)
- return mat_mult(B, B)
- else:
- return mat_mult(A, mat_pow(A, n-1))
- F = [[1, 1], [1, 0]]
- return mat_pow(F, n-1)[0][0]
Advertisement
Add Comment
Please, Sign In to add comment