Skip to content

Instantly share code, notes, and snippets.

@aershov24
Created October 13, 2020 05:28
Show Gist options
  • Select an option

  • Save aershov24/326475df8f1b3d66307f0fdeca147e33 to your computer and use it in GitHub Desktop.

Select an option

Save aershov24/326475df8f1b3d66307f0fdeca147e33 to your computer and use it in GitHub Desktop.
Markdium-14 Fibonacci Interview Questions (SOLVED) To Brush Before Coding Interview
class Solution:
def fib(self, N: int) -> int:
if (N <= 1):
return N
A = [[1, 1], [1, 0]]
self.matrix_power(A, N-1)
return A[0][0]
def matrix_power(self, A: list, N: int):
if (N <= 1):
return A
self.matrix_power(A, N//2)
self.multiply(A, A)
B = [[1, 1], [1, 0]]
if (N%2 != 0):
self.multiply(A, B)
def multiply(self, A: list, B: list):
x = A[0][0] * B[0][0] + A[0][1] * B[1][0]
y = A[0][0] * B[0][1] + A[0][1] * B[1][1]
z = A[1][0] * B[0][0] + A[1][1] * B[1][0]
w = A[1][0] * B[0][1] + A[1][1] * B[1][1]
A[0][0] = x
A[0][1] = y
A[1][0] = z
A[1][1] = w
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment