Guest User

ChatGPT fibonacci answer

a guest
Feb 4th, 2023
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.72 KB | None | 0 0
  1. #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."
  2.  
  3. def fib(n):
  4.     if n == 0:
  5.         return 0
  6.     if n == 1:
  7.         return 1
  8.  
  9.     def mat_mult(A, B):
  10.         C = [[0, 0], [0, 0]]
  11.         for i in range(2):
  12.             for j in range(2):
  13.                 C[i][j] = A[i][0] * B[0][j] + A[i][1] * B[1][j]
  14.         return C
  15.  
  16.     def mat_pow(A, n):
  17.         if n == 1:
  18.             return A
  19.         if n % 2 == 0:
  20.             B = mat_pow(A, n//2)
  21.             return mat_mult(B, B)
  22.         else:
  23.             return mat_mult(A, mat_pow(A, n-1))
  24.  
  25.     F = [[1, 1], [1, 0]]
  26.     return mat_pow(F, n-1)[0][0]
  27.  
Advertisement
Add Comment
Please, Sign In to add comment