progress

~/problems / Number theory / Matrix exponentiation

Matrix multiply and matrix power

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Matrix-exponentiation tricks (huge Fibonacci numbers, linear recurrences, counting walks) sit on two small functions. Write them generically, reducing every entry modulo mod:

  1. mat_mul(A, B, mod): the product of an n × m matrix A and an m × p matrix B (lists of rows): entry (i, j) is Σ A[i][t] · B[t][j] % mod.
  2. mat_pow(M, e, mod): square matrix M to the power e; M^0 is the identity.
mat_mul([[1, 2], [3, 4]], [[5, 6], [7, 8]], 1000)   # [[19, 22], [43, 50]]
mat_mul([[1, 2, 3]], [[4], [5], [6]], 10)          # [[2]]   (32 % 10)
mat_pow([[1, 1], [1, 0]], 10, 10**9 + 7)          # [[89, 55], [55, 34]]   (Fibonacci numbers)
mat_pow([[2, 0], [0, 3]], 0, 7)                   # [[1, 0], [0, 1]]

Don't modify the inputs. Dimensions up to 8, 0 <= e <= 10^18, 1 <= mod <= 2·10^9.

⭐ Bonus: multiplying e times passes for small e; a speed test with e up to 10^18 earns a star with repeated squaring (about 60 squarings).

Show hint

result = identity, base = M; while e > 0: if e & 1, result = result · base; then base = base · base, e >>= 1.

Topic: Matrix exponentiation. Linear recurrences in O(k^3 log n).

0:00
Ctrl ' run · Ctrl ↵ submit
esc