Advertisement
Guest User

matrixfib.py

a guest
Feb 13th, 2017
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. class MatrixFibonacci:
  2. Q = [[1, 1],[1, 0]]
  3.  
  4. def __init__(self):
  5. self.__memo = {}
  6.  
  7. def __mutiply_matrices(self, M1, M2):
  8. a11 = M1[0][0]*M2[0][0] + M1[0][1]*M2[1][0]
  9. a12 = M1[0][0]*M2[0][1] + M1[0][1]*M2[1][1]
  10. a21 = M1[1][0]*M2[0][0] + M1[1][1]*M2[1][0]
  11. a22 = M1[1][0]*M2[0][1] + M1[1][1]*M2[1][1]
  12. r = [[a11, a12], [a21, a22]]
  13. return r
  14.  
  15. def __get_matrix_power(self, M, p):
  16. if p == 1:
  17. return M
  18. if p in self.__memo:
  19. return self.__memo[p]
  20. K = self.__get_matrix_power(M, int(p/2))
  21. R = self.__multiply_matrices(K, K)
  22. self.__memo[p] = R
  23. return R
  24.  
  25. def get_number(self, n):
  26. if n == 0:
  27. return 0
  28. if n == 1:
  29. return 1
  30. powers = [int(pow(2, b))
  31. for (b, d) in enumerate(reversed(bin(n-1)[2:])) if d == '1']
  32. matrices = [self.__get_matrix_power(MatrixFibonacci.Q, p) for p in powers]
  33. while len(matrices) > 1:
  34. M1 = matrices.pop()
  35. M2 = matrices.pop()
  36. R = self.__multiply_matrices(M1, M2)
  37. matrices.append(R)
  38. return matrices[0][0][0]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement