Solve a linear system exactly

Solve n linear equations in n unknowns with whole-number coefficients.

Input

A whole number n (1 to 6), then n lines of n + 1 whole numbers: the coefficients of x1 … xn, then the right-hand side.

Output

If there is exactly one solution, n lines x1 = V, x2 = V, …, where each V is a whole number or a fraction in lowest terms such as -3/2. Otherwise print no unique solution.

Examples

Example 1 · Input
2
2 1 5
1 -1 1
Expected output
x1 = 2
x2 = 1
Example 2 · Input
3
2 1 -1 8
-3 -1 2 -11
-2 1 2 -3
Expected output
x1 = 2
x2 = 3
x3 = -1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Store every number as a fractions.Fraction so nothing is rounded.

Hint 2

For each column, find a row at or below it with a non-zero entry and swap it up; if there is none, there is no unique solution.

Hint 3

Clear the column in every other row, then x = right side ÷ pivot. str() of a Fraction prints 3/2 or 2.

Solution

Show one correct solution (try it yourself first)
from fractions import Fraction

n = int(input())
rows = [[Fraction(int(x)) for x in input().split()] for _ in range(n)]
unique = True
for col in range(n):
    pivot = next((r for r in range(col, n) if rows[r][col] != 0), None)
    if pivot is None:
        unique = False
        break
    rows[col], rows[pivot] = rows[pivot], rows[col]
    for r in range(n):
        if r != col and rows[r][col] != 0:
            factor = rows[r][col] / rows[col][col]
            rows[r] = [a - factor * b for a, b in zip(rows[r], rows[col])]
if unique:
    for i in range(n):
        print(f"x{i + 1} = {rows[i][n] / rows[i][i]}")
else:
    print("no unique solution")

Lesson: Solving systems of linear equations →