TExcelTAD
Home › Linear Algebra & Matrix Theory › Application: Cramer's Rule

Application: Cramer's Rule

Cramer's rule writes the solution of a square linear system Ax=bA\mathbf{x} = \mathbf{b} as ratios of determinants, one variable at a time. It is elegant, it gives closed-form formulas for small and symbolic systems (including a famous ray–triangle test in graphics), and it is a terrible general-purpose solver: with cofactor expansion its cost grows like n!n!, against n3n^3 for elimination. This lesson shows all three sides and times the difference.

The rule

Let AA be an invertible n×nn \times n matrix. For each ii, let Ai(b)A_i(\mathbf{b}) be AA with column ii replaced by b\mathbf{b}. Then the unique solution of Ax=bA\mathbf{x} = \mathbf{b} is

xi=det⁡Ai(b)det⁡A,i=1,…,nx_i = \frac{\det A_i(\mathbf{b})}{\det A}, \qquad i = 1, \ldots, n

2×22 \times 2 example. Solve 3x+2y=73x + 2y = 7, x−4y=7x - 4y = 7:

det⁡A=det⁡[321−4]=−12−2=−14det⁡A1(b)=det⁡[727−4]=−28−14=−42x=−42/−14=3det⁡A2(b)=det⁡[3717]=21−7=14y=14/−14=−1check: 3⋅3+2⋅(−1)=7 ✓,3−4⋅(−1)=7 ✓\begin{aligned} \det A &= \det \begin{bmatrix} 3 & 2 \\ 1 & -4 \end{bmatrix} = -12 - 2 = -14 \\ \det A_1(\mathbf{b}) &= \det \begin{bmatrix} 7 & 2 \\ 7 & -4 \end{bmatrix} = -28 - 14 = -42 && x = -42 / -14 = 3 \\ \det A_2(\mathbf{b}) &= \det \begin{bmatrix} 3 & 7 \\ 1 & 7 \end{bmatrix} = 21 - 7 = 14 && y = 14 / -14 = -1 \\ \text{check: } & 3 \cdot 3 + 2 \cdot (-1) = 7 \ \checkmark, \quad 3 - 4 \cdot (-1) = 7 \ \checkmark \end{aligned}

Proof. Let XiX_i be the identity matrix with column ii replaced by x\mathbf{x}. Then AXiAX_i has columns Ae1,…,Ax,…,AenA\mathbf{e}_1, \ldots, A\mathbf{x}, \ldots, A\mathbf{e}_n, which are the columns of AA with column ii replaced by Ax=bA\mathbf{x} = \mathbf{b}: AXi=Ai(b)AX_i = A_i(\mathbf{b}). Expanding det⁡Xi\det X_i along row ii gives det⁡Xi=xi\det X_i = x_i. So by multiplicativity (Properties of Determinants), det⁡A⋅xi=det⁡Ai(b)\det A \cdot x_i = \det A_i(\mathbf{b}). ∎

Equivalently, Cramer's rule is the inverse formula x=A−1b=adj⁡(A)b/det⁡A\mathbf{x} = A^{-1}\mathbf{b} = \operatorname{adj}(A)\mathbf{b} / \det A (Application: A Formula for the Inverse) written out entry by entry.

python · try it yourself
from sympy import Matrix, symbols, simplify

def cramer(A, b):
    d = A.det()
    xs = []
    for i in range(A.cols):
        Ai = A.copy()
        Ai[:, i] = b                                     # replace column i by b
        xs.append(Ai.det() / d)
    return xs

A = Matrix([[2, 1, -1], [1, 3, 2], [3, -1, 4]])
b = Matrix([1, 13, 13])
print("Cramer:", cramer(A, b), " solve:", list(A.solve(b)))

# symbolic: a general 2x2 system
a11, a12, a21, a22, b1, b2 = symbols("a11 a12 a21 a22 b1 b2")
x, y = cramer(Matrix([[a11, a12], [a21, a22]]), Matrix([b1, b2]))
print("x =", simplify(x))
Cramer: [1, 2, 3]  solve: [1, 2, 3]
x = (-a12*b2 + a22*b1)/(a11*a22 - a12*a21)

The symbolic answer is a closed formula: x=b1a22−a12b2a11a22−a12a21x = \frac{b_1a_{22} - a_{12}b_2}{a_{11}a_{22} - a_{12}a_{21}}. Such formulas show, for example, that the solution of an integer system is a fraction with denominator det⁡A\det A, and how the solution changes when one coefficient changes.

Why it is slow: n!n! versus n3n^3

Cramer's rule needs n+1n + 1 determinants of size nn. With cofactor expansion (Minors and Cofactors) each costs on the order of n!n! multiplications (about e⋅n!e \cdot n!), so the whole rule is on the order of (n+1)⋅n!(n + 1) \cdot n!. Gaussian elimination needs about 23n3\frac{2}{3}n^3 operations. Count and time both on the same systems:

python · try it yourself
import time
import numpy as np

mults = 0
def det_cofactor(M):
    global mults
    n = len(M)
    if n == 1:
        return M[0][0]
    total = 0.0
    for j in range(n):
        minor = [row[:j] + row[j + 1:] for row in M[1:]]
        mults += 1
        total += (-1) ** j * M[0][j] * det_cofactor(minor)
    return total

def cramer_cofactor(A, b):
    d = det_cofactor(A)
    return [det_cofactor([row[:i] + [bi] + row[i + 1:] for row, bi in zip(A, b)]) / d
            for i in range(len(A))]

rng = np.random.default_rng(1)
for n in (3, 5, 7, 8):
    A = rng.normal(size=(n, n)); b = rng.normal(size=n)
    mults = 0
    t0 = time.perf_counter(); x1 = cramer_cofactor(A.tolist(), b.tolist()); t1 = time.perf_counter()
    x2 = np.linalg.solve(A, b); t2 = time.perf_counter()
    print(f"n = {n}: Cramer mults = {mults:6d}   elimination ~ {round(2 * n**3 / 3):3d} flops   "
          f"same answer: {np.allclose(x1, x2)}")
print("n = 8: np.linalg.solve faster than Cramer:", (t2 - t1) < (t1 - t0))
n = 3: Cramer mults =     36   elimination ~  18 flops   same answer: True
n = 5: Cramer mults =   1230   elimination ~  83 flops   same answer: True
n = 7: Cramer mults =  69272   elimination ~ 229 flops   same answer: True
n = 8: Cramer mults = 623520   elimination ~ 341 flops   same answer: True
n = 8: np.linalg.solve faster than Cramer: True

The multiplication count grows by a factor of about n+1n + 1 at every step; elimination barely moves. Extrapolating: for n=20n = 20, Cramer with cofactor expansion would need more than 102010^{20} multiplications (years of CPU time), while np.linalg.solve handles a 20×2020 \times 20 system in microseconds and a 2000×20002000 \times 2000 one in well under a second.

Even computing each determinant by elimination (O(n3)O(n^3)) leaves Cramer at O(n4)O(n^4), still nn times slower than solving once. And numerically, ratios of determinants are less stable than LU with pivoting.

Where Cramer's rule is the right tool

  • Tiny systems in hot loops. For 2×22 \times 2 and 3×33 \times 3 systems, Cramer's closed form is branch-free and fast. The classic Möller–Trumbore ray–triangle intersection solves the 3×33 \times 3 system origin+t⋅dir=v0+u⋅e1+v⋅e2\text{origin} + t \cdot \text{dir} = \mathbf{v}_0 + u \cdot \mathbf{e}_1 + v \cdot \mathbf{e}_2 exactly this way, with the determinants written as cross and dot products (scalar triple products) (Ray–Triangle).
  • Line intersection in 2D: two lines a1x+b1y=c1a_1x + b_1y = c_1 and a2x+b2y=c2a_2x + b_2y = c_2 meet at Cramer's formulas, and det⁡A=0\det A = 0 signals parallel lines, a test every 2D geometry library contains.
  • Symbolic work and proofs: it shows the solution is a rational function of the coefficients, which is used for sensitivity analysis and in theory (for example, integer systems with det⁡±1\det \pm 1 have integer solutions).

Exercises

Exercise 1: A 2×22 \times 2 system

Solve 5x−2y=15x - 2y = 1, 3x+4y=243x + 4y = 24 with Cramer's rule.

Answer

x=2x = 2, y=92y = \frac{9}{2}.

Solution
det⁡A=5⋅4−(−2)⋅3=26det⁡A1=det⁡[1−2244]=4+48=52x=5226=2det⁡A2=det⁡[51324]=120−3=117y=11726=92check: 10−9=1 ✓,6+18=24 ✓\begin{aligned} \det A &= 5 \cdot 4 - (-2) \cdot 3 = 26 \\ \det A_1 &= \det \begin{bmatrix} 1 & -2 \\ 24 & 4 \end{bmatrix} = 4 + 48 = 52 && x = \frac{52}{26} = 2 \\ \det A_2 &= \det \begin{bmatrix} 5 & 1 \\ 3 & 24 \end{bmatrix} = 120 - 3 = 117 && y = \frac{117}{26} = \frac{9}{2} \\ \text{check: } & 10 - 9 = 1 \ \checkmark, \quad 6 + 18 = 24 \ \checkmark \end{aligned}

Exercise 2: One unknown of a 3×33 \times 3 system

Find only zz in the system x+y+z=6x + y + z = 6, 2x−y+3z=132x - y + 3z = 13, x+2y−z=2x + 2y - z = 2.

Answer

z=115z = \frac{11}{5}.

Solution
det⁡A=det⁡[1112−1312−1]=1(1−6)−1(−2−3)+1(4+1)=−5+5+5=5det⁡A3=det⁡[1162−113122]=1(−2−26)−1(4−13)+6(4+1)=−28+9+30=11z=115\begin{aligned} \det A &= \det \begin{bmatrix} 1 & 1 & 1 \\ 2 & -1 & 3 \\ 1 & 2 & -1 \end{bmatrix} \\ &= 1(1 - 6) - 1(-2 - 3) + 1(4 + 1) = -5 + 5 + 5 = 5 \\ \det A_3 &= \det \begin{bmatrix} 1 & 1 & 6 \\ 2 & -1 & 13 \\ 1 & 2 & 2 \end{bmatrix} \\ &= 1(-2 - 26) - 1(4 - 13) + 6(4 + 1) = -28 + 9 + 30 = 11 \\ z &= \frac{11}{5} \end{aligned}

Check with code:

python · try it yourself
from sympy import Matrix
A = Matrix([[1, 1, 1], [2, -1, 3], [1, 2, -1]])
b = Matrix([6, 13, 2])
A3 = A.copy(); A3[:, 2] = b
print(A.det(), A3.det(), A3.det() / A.det(), list(A.solve(b)))
5 11 11/5 [17/5, 2/5, 11/5]

The full solution is x=175x = \frac{17}{5}, y=25y = \frac{2}{5}, z=115z = \frac{11}{5}; Cramer's rule gave zz without computing the other two.

Exercise 3: Intersect two lines

Use Cramer's rule to intersect 2x+3y=122x + 3y = 12 and x−y=1x - y = 1. Then explain what det⁡A=0\det A = 0 would mean geometrically.

Answer

(3,2)(3, 2). det⁡A=0\det A = 0 means the lines are parallel (or the same line).

Solution
det⁡A=2⋅(−1)−3⋅1=−5det⁡A1=12⋅(−1)−3⋅1=−15x=3det⁡A2=2⋅1−12⋅1=−10y=2\begin{aligned} \det A &= 2 \cdot (-1) - 3 \cdot 1 = -5 \\ \det A_1 &= 12 \cdot (-1) - 3 \cdot 1 = -15 && x = 3 \\ \det A_2 &= 2 \cdot 1 - 12 \cdot 1 = -10 && y = 2 \end{aligned}

det⁡A=0\det A = 0 means the normal vectors [a1,b1][a_1, b_1] and [a2,b2][a_2, b_2] are parallel, so the lines are parallel: no intersection, or infinitely many if they coincide.

Exercise 4: Estimate the cost

Using the rough estimate (n+1)⋅n!(n + 1) \cdot n! for Cramer with cofactor expansion, estimate the multiplications for n=12n = 12 and compare with 23n3\frac{2}{3}n^3.

Answer

About 6.2×1096.2 \times 10^9 versus 1152.

Solution
python · try it yourself
from math import factorial
n = 12
print(f"{(n + 1) * factorial(n):.2e}", round(2 * n**3 / 3))
6.23e+09 1152

Billions of multiplications against about a thousand, a ratio of more than five million.

Test yourself

In Cramer's rule, how is A2(b)A_2(\mathbf{b}) formed?

  1. Replace row 2 of AA with b\mathbf{b}
  2. Multiply column 2 by b\mathbf{b}
  3. Delete row and column 2
  4. Replace column 2 of AA with b\mathbf{b}

Why is Cramer's rule with cofactor expansion unsuitable for a 50×5050 \times 50 system?

  1. It gives wrong answers
  2. It only works for symmetric matrices
  3. Its cost grows like n!n!, astronomically more than elimination's n3n^3
  4. It needs complex numbers

Where is Cramer's rule genuinely used in practice?

  1. Training large neural networks
  2. Small fixed-size systems such as ray–triangle intersection
  3. Solving sparse 106×10610^6 \times 10^6 systems
  4. Never