mpinvert.c 806 B

123456789101112131415161718192021222324252627282930
  1. /*
  2. * This file is part of the UCB release of Plan 9. It is subject to the license
  3. * terms in the LICENSE file found in the top-level directory of this
  4. * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
  5. * part of the UCB release of Plan 9, including this file, may be copied,
  6. * modified, propagated, or distributed except according to the terms contained
  7. * in the LICENSE file.
  8. */
  9. #include "os.h"
  10. #include <mp.h>
  11. #define iseven(a) (((a)->p[0] & 1) == 0)
  12. // use extended gcd to find the multiplicative inverse
  13. // res = b**-1 mod m
  14. void
  15. mpinvert(mpint *b, mpint *m, mpint *res)
  16. {
  17. mpint *dc1, *dc2; // don't care
  18. dc1 = mpnew(0);
  19. dc2 = mpnew(0);
  20. mpextendedgcd(b, m, dc1, res, dc2);
  21. if(mpcmp(dc1, mpone) != 0)
  22. abort();
  23. mpmod(res, m, res);
  24. mpfree(dc1);
  25. mpfree(dc2);
  26. }