TExcelTAD
Home › Linear Algebra & Matrix Theory › Matrix Arithmetic Modulo p

Matrix Arithmetic Modulo p

Everything we have done with matrices (addition, multiplication, row reduction, inverses) works with any field of scalars, not just the real numbers. For a prime pp, the integers modulo pp form a field Zp\mathbb{Z}_p, and matrix arithmetic over Zp\mathbb{Z}_p powers cryptography, error-correcting codes and checksums.

Arithmetic in Zp\mathbb{Z}_p

Zp={0,1,…,p−1}\mathbb{Z}_p = \{0, 1, \ldots, p - 1\}, where you add and multiply as usual and then take the remainder after division by pp:

in Z7:5+4=9≡2,3⋅5=15≡1,2−6=−4≡3\text{in } \mathbb{Z}_7: \quad 5 + 4 = 9 \equiv 2, \qquad 3 \cdot 5 = 15 \equiv 1, \qquad 2 - 6 = -4 \equiv 3

The key property: when pp is prime, every non-zero element has a multiplicative inverse. In Z7\mathbb{Z}_7, 3⋅5≡13 \cdot 5 \equiv 1, so 3−1=53^{-1} = 5. You can find inverses with the extended Euclidean algorithm, or in Python with pow(a, -1, p). (For composite nn, Zn\mathbb{Z}_n is not a field: in Z6\mathbb{Z}_6, 2⋅3≡02 \cdot 3 \equiv 0 and 2 has no inverse.)

aa in Z7\mathbb{Z}_7 1 2 3 4 5 6
a−1a^{-1} 1 4 5 2 3 6

Because Zp\mathbb{Z}_p is a field, every algorithm built from ++, −-, ×\times and ÷\div by non-zero numbers works unchanged. That includes Gaussian elimination.

Matrix operations mod p

Add and multiply matrices as usual, then reduce every entry mod pp. To row-reduce, "divide a row by its pivot" means "multiply by the pivot's inverse mod pp".

python · try it yourself
from sympy import Matrix

p = 7
A = Matrix([[3, 5], [6, 2]])
B = Matrix([[4, 1], [2, 6]])
print("A + B mod 7:", ((A + B) % p).tolist())
print("A * B mod 7:", ((A * B) % p).tolist())

Ainv = A.inv_mod(p)
print("A^-1 mod 7:", Ainv.tolist())
print("A * A^-1 mod 7:", ((A * Ainv) % p).tolist())
print("inverse of 3 mod 7:", pow(3, -1, 7))
A + B mod 7: [[0, 6], [1, 1]]
A * B mod 7: [[1, 5], [0, 4]]
A^-1 mod 7: [[4, 4], [2, 6]]
A * A^-1 mod 7: [[1, 0], [0, 1]]
inverse of 3 mod 7: 5

The 2×2 inverse formula still works, with "divide by ad−bcad - bc" replaced by "multiply by (ad−bc)−1 mod p(ad - bc)^{-1} \bmod p" (Exercise 1 does it by hand for this AA).

Solving a system mod p

Here is Gaussian elimination written for Zp\mathbb{Z}_p in plain Python. It is the familiar algorithm with pow(pivot, -1, p) in place of division:

python · try it yourself
def solve_mod(A, b, p):
    n = len(A)
    M = [row[:] + [bi] for row, bi in zip(A, b)]
    for col in range(n):
        piv = next(r for r in range(col, n) if M[r][col] % p != 0)  # find a pivot
        M[col], M[piv] = M[piv], M[col]
        inv = pow(M[col][col], -1, p)
        M[col] = [(v * inv) % p for v in M[col]]                       # scale pivot to 1
        for r in range(n):
            if r != col and M[r][col] % p:
                f = M[r][col]
                M[r] = [(v - f * w) % p for v, w in zip(M[r], M[col])]
    return [row[-1] for row in M]

A = [[2, 3, 1], [1, 4, 5], [3, 1, 2]]
b = [1, 0, 4]
x = solve_mod(A, b, 11)
print("x =", x)
print("check A x mod 11:", [sum(a * xi for a, xi in zip(row, x)) % 11 for row in A])
x = [3, 10, 9]
check A x mod 11: [1, 0, 4]

When is a matrix invertible mod pp?

A square matrix with integer entries is invertible mod pp exactly when its determinant is not divisible by pp. So the same integer matrix can be invertible over Q\mathbb{Q} but singular mod some primes:

python · try it yourself
from sympy import Matrix

A = Matrix([[2, 1], [1, 4]])          # det = 7
print("det over the integers:", A.det())
for p in [2, 3, 5, 7, 11]:
    ok = A.det() % p != 0
    print(f"p = {p:2d}: det mod p = {A.det() % p}  invertible: {ok}")
print("rank mod 7 is 1, row 2 ≡ 4·row 1:", ((4 * A.row(0)) % 7).tolist(), A.row(1).tolist())
det over the integers: 7
p =  2: det mod p = 1  invertible: True
p =  3: det mod p = 1  invertible: True
p =  5: det mod p = 2  invertible: True
p =  7: det mod p = 0  invertible: False
p = 11: det mod p = 7  invertible: True
rank mod 7 is 1, row 2 ≡ 4·row 1: [[1, 4]] [[1, 4]]

Z2\mathbb{Z}_2: linear algebra with bits

In Z2={0,1}\mathbb{Z}_2 = \{0, 1\}, addition is XOR and multiplication is AND. A vector over Z2\mathbb{Z}_2 is a bit string and a matrix over Z2\mathbb{Z}_2 is a grid of bits, so matrix–vector products are XORs of selected rows. That makes Z2\mathbb{Z}_2 linear algebra extremely fast in hardware.

In software

  • Error-correcting codes: Hamming codes, used in ECC memory, encode a 4-bit message as a 7-bit codeword with a 4×7 generator matrix over Z2\mathbb{Z}_2; a 3×7 parity-check matrix finds and fixes any single flipped bit (Application: Error Correcting Codes).
  • Checksums: CRCs (Ethernet, ZIP, PNG) are linear maps over Z2\mathbb{Z}_2 computed with shifts and XORs.
  • Cryptography: AES mixes bytes with a fixed matrix over the field GF(28)\mathrm{GF}(2^8) with 256 elements (MixColumns); the classical Hill cipher uses matrices mod 26 (Application: Cryptography).
  • Puzzles and algorithms: the "Lights Out" puzzle is a linear system over Z2\mathbb{Z}_2; Gaussian elimination over Z2\mathbb{Z}_2 solves it, and also appears in factoring algorithms (the quadratic sieve).
  • Integer overflow: arithmetic on 32-bit unsigned integers is arithmetic mod 2322^{32}, which is a ring, not a field, because 2322^{32} is not prime: even numbers have no inverse.

Exercises

Exercise 1: Inverse mod 7 by formula

Compute the inverse of A=[3562] mod 7A = \begin{bmatrix} 3 & 5 \\ 6 & 2 \end{bmatrix} \bmod 7 with the 2×2 formula and compare with the SymPy result above.

Answer

A−1≡[4426](mod7)A^{-1} \equiv \begin{bmatrix} 4 & 4 \\ 2 & 6 \end{bmatrix} \pmod{7}.

Solution
ad−bc=3⋅2−5⋅6=6−30=−24≡−24+28=4(mod7)4−1 mod 7=2,since 4⋅2=8≡1adjugate [d−b−ca]=[2−5−63]≡[2213]A−1≡2⋅[2213]=[4426]\begin{aligned} ad - bc &= 3 \cdot 2 - 5 \cdot 6 = 6 - 30 = -24 \equiv -24 + 28 = 4 \pmod{7} \\ 4^{-1} \bmod 7 &= 2, \quad \text{since } 4 \cdot 2 = 8 \equiv 1 \\ \text{adjugate } \begin{bmatrix} d & -b \\ -c & a \end{bmatrix} &= \begin{bmatrix} 2 & -5 \\ -6 & 3 \end{bmatrix} \equiv \begin{bmatrix} 2 & 2 \\ 1 & 3 \end{bmatrix} \\ A^{-1} &\equiv 2 \cdot \begin{bmatrix} 2 & 2 \\ 1 & 3 \end{bmatrix} = \begin{bmatrix} 4 & 4 \\ 2 & 6 \end{bmatrix} \end{aligned}

Check: A[4426]=[12+1012+3024+424+12]=[22422836]≡[1001](mod7)A \begin{bmatrix} 4 & 4 \\ 2 & 6 \end{bmatrix} = \begin{bmatrix} 12 + 10 & 12 + 30 \\ 24 + 4 & 24 + 12 \end{bmatrix} = \begin{bmatrix} 22 & 42 \\ 28 & 36 \end{bmatrix} \equiv \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} \pmod{7}.

python · try it yourself
from sympy import Matrix
A = Matrix([[3, 5], [6, 2]])
X = Matrix([[4, 4], [2, 6]])
print(((A * X) % 7).tolist(), X == A.inv_mod(7))
[[1, 0], [0, 1]] True

Exercise 2: Inverses in Z13\mathbb{Z}_{13}

Find 5−15^{-1} and 7−17^{-1} in Z13\mathbb{Z}_{13}.

Answer

5−1=85^{-1} = 8 and 7−1=27^{-1} = 2.

Solution

5⋅8=40=3⋅13+1≡15 \cdot 8 = 40 = 3 \cdot 13 + 1 \equiv 1, and 7⋅2=14≡17 \cdot 2 = 14 \equiv 1. In Python: pow(5, -1, 13) → 8, pow(7, -1, 13) → 2.

Exercise 3: Which primes break it?

For A=[4236]A = \begin{bmatrix} 4 & 2 \\ 3 & 6 \end{bmatrix}, list the primes pp for which AA is not invertible mod pp.

Answer

p=2p = 2 and p=3p = 3.

Solution

det⁡A=24−6=18=2⋅32\det A = 24 - 6 = 18 = 2 \cdot 3^2. AA is singular mod pp exactly when pp divides 18, i.e. p=2p = 2 or p=3p = 3.

Exercise 4: Solve over Z2\mathbb{Z}_2

Solve over Z2\mathbb{Z}_2: x1+x2=1x_1 + x_2 = 1, x2+x3=0x_2 + x_3 = 0, x1+x3=1x_1 + x_3 = 1, x1+x2+x3=0x_1 + x_2 + x_3 = 0 (four equations, three unknowns). Reason with XOR, then confirm by brute force over all 8 bit vectors.

Answer

Exactly one solution: (x1,x2,x3)=(0,1,1)(x_1, x_2, x_3) = (0, 1, 1).

Solution
eq 1: x1=1+x2eq 2: x3=x2(in Z2, −1=+1)eq 3: x1+x3=1+2x2≡1always true, so eq 3 is redundanteq 4: x1+x2+x3=1+3x2≡1+x2=0  →  x2=1eq 4: x1=0,x3=1check: 0+1=1✓1+1=0✓0+1=1✓0+1+1=0✓\begin{aligned} &\text{eq 1: } x_1 = 1 + x_2 \qquad \text{eq 2: } x_3 = x_2 && \text{(in } \mathbb{Z}_2,\ -1 = +1\text{)} \\ &\text{eq 3: } x_1 + x_3 = 1 + 2x_2 \equiv 1 && \text{always true, so eq 3 is redundant} \\ &\text{eq 4: } x_1 + x_2 + x_3 = 1 + 3x_2 \equiv 1 + x_2 = 0 \;\to\; x_2 = 1 \\ &\phantom{\text{eq 4: }} x_1 = 0, \quad x_3 = 1 \\ &\text{check: } 0 + 1 = 1 \checkmark \quad 1 + 1 = 0 \checkmark \quad 0 + 1 = 1 \checkmark \quad 0 + 1 + 1 = 0 \checkmark \end{aligned}

Brute force confirms it is the only one:

python · try it yourself
from itertools import product
eqs = [((1, 1, 0), 1), ((0, 1, 1), 0), ((1, 0, 1), 1), ((1, 1, 1), 0)]
sols = [x for x in product([0, 1], repeat=3)
        if all(sum(a * xi for a, xi in zip(c, x)) % 2 == r for c, r in eqs)]
print(sols)
[(0, 1, 1)]

Test yourself

What is 4−14^{-1} in Z11\mathbb{Z}_{11}?

  1. It does not exist
  2. 4
  3. 7
  4. 3

An integer matrix has determinant 15. Modulo which prime is it NOT invertible?

  1. 2
  2. 7
  3. 5
  4. 11

In Z2\mathbb{Z}_2, what operation is addition of bits?

  1. AND
  2. XOR
  3. OR
  4. NAND