Determinant of a matrix

Print the determinant of a square matrix of whole numbers.

Input

A whole number n (1 to 8), then n lines of n whole numbers.

Output

The determinant, a whole number.

Examples

Example 1 · Input
2
4 7
2 6
Expected output
10
Example 2 · Input
3
2 0 1
1 3 2
1 1 2
Expected output
6

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

Hints

Hint 1

Run elimination: the determinant is the product of the pivots.

Hint 2

Each row swap flips the sign. If a column has no non-zero pivot left, the determinant is 0.

Hint 3

fractions.Fraction keeps every step exact.

Solution

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

n = int(input())
m = [[Fraction(int(x)) for x in input().split()] for _ in range(n)]
det = Fraction(1)
for col in range(n):
    pivot = next((r for r in range(col, n) if m[r][col] != 0), None)
    if pivot is None:
        det = Fraction(0)
        break
    if pivot != col:
        m[col], m[pivot] = m[pivot], m[col]
        det = -det
    det *= m[col][col]
    for r in range(col + 1, n):
        factor = m[r][col] / m[col][col]
        m[r] = [a - factor * b for a, b in zip(m[r], m[col])]
print(int(det))

Lesson: Determinants and inverses →