Created
March 27, 2022 11:27
-
-
Save adigitoleo/35ad86cc2439235cae05a72b8fb193e6 to your computer and use it in GitHub Desktop.
Arbitrary precision modular matrix inverse in Julia
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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