def multiply_matrices(a, b): res = [[0, 0], [0, 0]] for i in range(0, 2): for j in range(0, 2): for p in range(0, 2): res[i][j] = (res[i][j] + a[i][p] * b[p][j]) % M return res b = 次方数 while b > 0: if b & 1: ans = multiply_matrices(ans, base) base = multiply_matrices(base, base) b >>= 1
例题
2024.11.SICTF#Round4.Math Cocktail
题目
1 2 3 4 5 6 7 8 9
from secret import key x = key M = 94665789456132156456789461321289656332321 n = 123456789123456789 k = x + pow(x,-1,M) result = pow(x,n,M) + pow(x,-n,M) print("k = " + str(k)) flag = "SICTF{"+str(result)+"}" #k = 15396893775857205606087136852231851457937
def multiply_matrices(a, b): res = [[0, 0], [0, 0]] for i in range(0, 2): for j in range(0, 2): for p in range(0, 2): res[i][j] = (res[i][j] + a[i][p] * b[p][j]) % M return res M = 94665789456132156456789461321289656332321 n = 123456789123456789 k = 15396893775857205606087136852231851457937 base = [[k, 1], [-1, 0]] ans = [[(k*k-2) % M, k % M], [0, 0]] b = n - 2 while b > 0: if b & 1: ans = multiply_matrices(ans, base) base = multiply_matrices(base, base) b >>= 1 print((ans[0][0] + M) % M)