xref: /plan9/sys/src/cmd/unix/drawterm/libmp/mpinvert.c (revision 8ccd4a6360d974db7bd7bbd4f37e7018419ea908)
1 #include "os.h"
2 #include <mp.h>
3 
4 #define iseven(a)	(((a)->p[0] & 1) == 0)
5 
6 // use extended gcd to find the multiplicative inverse
7 // res = b**-1 mod m
8 void
mpinvert(mpint * b,mpint * m,mpint * res)9 mpinvert(mpint *b, mpint *m, mpint *res)
10 {
11 	mpint *dc1, *dc2;	// don't care
12 
13 	dc1 = mpnew(0);
14 	dc2 = mpnew(0);
15 	mpextendedgcd(b, m, dc1, res, dc2);
16 	if(mpcmp(dc1, mpone) != 0)
17 		abort();
18 	mpmod(res, m, res);
19 	mpfree(dc1);
20 	mpfree(dc2);
21 }
22