libmp: allow passing nil to v,x,y results of mpextendedgcd(), simplify mpinvert()

This commit is contained in:
cinap_lenrek 2016-08-29 02:07:52 +02:00
parent 33862ff793
commit 5852f8a144
2 changed files with 14 additions and 12 deletions

View file

@ -15,8 +15,16 @@ mpextendedgcd(mpint *a, mpint *b, mpint *v, mpint *x, mpint *y)
mpint *u, *A, *B, *C, *D;
int g;
if(v == nil){
v = mpnew(0);
mpextendedgcd(a, b, v, x, y);
mpfree(v);
return;
}
assert(x == nil || (x->flags & MPtimesafe) == 0);
assert(y == nil || (y->flags & MPtimesafe) == 0);
assert((a->flags&b->flags) & MPnorm);
assert(((a->flags|b->flags|v->flags|x->flags|y->flags) & MPtimesafe) == 0);
assert(((a->flags|b->flags|v->flags) & MPtimesafe) == 0);
if(a->sign < 0 || b->sign < 0){
mpassign(mpzero, v);
@ -104,6 +112,4 @@ mpextendedgcd(mpint *a, mpint *b, mpint *v, mpint *x, mpint *y)
mpfree(u);
mpfree(a);
mpfree(b);
return;
}

View file

@ -1,21 +1,17 @@
#include "os.h"
#include <mp.h>
#define iseven(a) (((a)->p[0] & 1) == 0)
// use extended gcd to find the multiplicative inverse
// res = b**-1 mod m
void
mpinvert(mpint *b, mpint *m, mpint *res)
{
mpint *dc1, *dc2; // don't care
mpint *v;
dc1 = mpnew(0);
dc2 = mpnew(0);
mpextendedgcd(b, m, dc1, res, dc2);
if(mpcmp(dc1, mpone) != 0)
v = mpnew(0);
mpextendedgcd(b, m, v, res, nil);
if(mpcmp(v, mpone) != 0)
abort();
mpfree(v);
mpmod(res, m, res);
mpfree(dc1);
mpfree(dc2);
}