CP Notebook

← all snippets

IntDeterminant

Calculates determinant using modular arithmetics. Modulos can also be removed to get a pure-integer version.

Time: O(N³) 18 lines bruteforce-tested for N <= 3, mod <= 7

content/numerical/IntDeterminant.h — Unknown, source: somewhere on github

const ll mod = 12345;
ll det(vector<vector<ll>>& a) {
	int n = sz(a); ll ans = 1;
	rep(i,0,n) {
		rep(j,i+1,n) {
			while (a[j][i] != 0) { // gcd step
				ll t = a[i][i] / a[j][i];
				if (t) rep(k,i,n)
					a[i][k] = (a[i][k] - a[j][k] * t) % mod;
				swap(a[i], a[j]);
				ans *= -1;
			}
		}
		ans = ans * a[i][i] % mod;
		if (!ans) return 0;
	}
	return (ans + mod) % mod;
}