Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Matrix:
- Q = [[0, 1],
- [1, 1]]
- def __init__(self):
- self.__memo = {} #add memorization
- def __multiply_matrices(self, M1, M2):# multiply two 2x2 matrices line by column
- a11 = M1[0][0]*M2[0][0] + M1[0][1]*M2[1][0]
- a12 = M1[0][0]*M2[0][1] + M1[0][1]*M2[1][1]
- a21 = M1[1][0]*M2[0][0] + M1[1][1]*M2[1][0]
- a22 = M1[1][0]*M2[0][1] + M1[1][1]*M2[1][1]
- r = [[a11, a12], [a21, a22]]
- return r
- def __get_matrix_power(self, M, p):
- if p == 1:# if p was 1 we return matrix itself
- return M
- if p in self.__memo:# if we've already counted this power we return reminded matrix
- return self.__memo[p]
- K = self.__get_matrix_power(M, int(p/2)) # recursively power matrix to p/2 power
- R = self.__multiply_matrices(K, K) #matrix to matrix power = 2
- self.__memo[p] = R# remind it
- return R
- def get_num(self, n):
- if n == 0:#start num
- return 0;
- if n == 1:#start num
- return 2;
- powers = []
- p = 0
- for digit in reversed(bin(n-1)[2:]):# get bit representation of number
- if digit == '1':
- powers.append(int(pow(2, p)))# if bit = 1 then there was 1*2^p in number -> remind 2^p
- p += 1
- matrices = [self.__get_matrix_power(Matrix.Q, p)
- for p in powers] #save all intermediate result
- while len(matrices) > 1:
- M1 = matrices.pop()
- M2 = matrices.pop()
- R = self.__multiply_matrices(M1, M2)#multiply them
- matrices.append(R)
- k = matrices[0][0][0] + matrices[0][1][0]# last matrix will contain all needed results
- mm = matrices[0][0][1] + matrices[0][1][1]
- return k + mm
- mat = Matrix()
- tt = int(input())
- num = mat.get_num(tt)
- print(num)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement