Created
December 17, 2021 20:02
-
-
Save AntonC9018/679f1b67052cf29567adf711643bc0e6 to your computer and use it in GitHub Desktop.
Inverse modulo via the euclidean algorithm
This file contains 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
long inverse_modulo(long a, long n) | |
{ | |
auto t0 = 0L; | |
auto t1 = 1L; | |
auto r0 = n; | |
auto r1 = a; | |
while (r1 != 0) | |
{ | |
auto q = r0 / r1; | |
auto r_new = r0 - q * r1; | |
r0 = r1; | |
r1 = r_new; | |
auto t_new = t0 - q * t1; | |
t0 = t1; | |
t1 = t_new; | |
} | |
if (r0 != 1) | |
return 0; | |
if (t0 < 0) | |
return t0 + n; | |
return t0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment