shithub: femtolisp

ref: 32b537dbdb56584c3dfdb9f95f1d1cec0359d7d7
dir: /3rd/mp/mpinvert.c/

View raw version
#include "platform.h"
#include "mp.h"

// use extended gcd to find the multiplicative inverse
// res = b**-1 mod m
void
mpinvert(mpint *b, mpint *m, mpint *res)
{
	mpint *v;

	v = mpnew(0);
	mpextendedgcd(b, m, v, res, nil);
	if(mpcmp(v, mpone) != 0){
		fprintf(stderr, "mpinvert: impossible\n");
		exit(2);
	}
	mpfree(v);
	mpmod(res, m, res);
}