Skip to content

Instantly share code, notes, and snippets.

@adigitoleo
Created March 27, 2022 11:27
Show Gist options
  • Save adigitoleo/35ad86cc2439235cae05a72b8fb193e6 to your computer and use it in GitHub Desktop.
Save adigitoleo/35ad86cc2439235cae05a72b8fb193e6 to your computer and use it in GitHub Desktop.
Arbitrary precision modular matrix inverse in Julia
using LinearAlgebra
function inverse(a::AbstractMatrix{BigInt}, modulus)
m, n = size(a)
if m - n != 0
error("cannot find modular inverse of non-square matrix")
end
det_inv = invmod(BigInt(det(a)), modulus)
if det_inv == 0
error("cannot invert singular matrix")
end
cofactors = Matrix{BigInt}(undef, size(a))
for i in 1:n
for j in 1:n
minor = det(view(a, setdiff(1:n, [i]), setdiff(1:n, [j])))
cofactors[i, j] = mod(-1, modulus)^(i+j) * minor
end
end
result = mod.(det_inv .* cofactors', modulus)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment