Blame mpz/invert.c

Packit 5c3484
/* mpz_invert (inv, x, n).  Find multiplicative inverse of X in Z(N).
Packit 5c3484
   If X has an inverse, return non-zero and store inverse in INVERSE,
Packit 5c3484
   otherwise, return 0 and put garbage in INVERSE.
Packit 5c3484
Packit 5c3484
Copyright 1996-2001, 2005, 2012, 2014 Free Software Foundation, Inc.
Packit 5c3484
Packit 5c3484
This file is part of the GNU MP Library.
Packit 5c3484
Packit 5c3484
The GNU MP Library is free software; you can redistribute it and/or modify
Packit 5c3484
it under the terms of either:
Packit 5c3484
Packit 5c3484
  * the GNU Lesser General Public License as published by the Free
Packit 5c3484
    Software Foundation; either version 3 of the License, or (at your
Packit 5c3484
    option) any later version.
Packit 5c3484
Packit 5c3484
or
Packit 5c3484
Packit 5c3484
  * the GNU General Public License as published by the Free Software
Packit 5c3484
    Foundation; either version 2 of the License, or (at your option) any
Packit 5c3484
    later version.
Packit 5c3484
Packit 5c3484
or both in parallel, as here.
Packit 5c3484
Packit 5c3484
The GNU MP Library is distributed in the hope that it will be useful, but
Packit 5c3484
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
Packit 5c3484
or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
Packit 5c3484
for more details.
Packit 5c3484
Packit 5c3484
You should have received copies of the GNU General Public License and the
Packit 5c3484
GNU Lesser General Public License along with the GNU MP Library.  If not,
Packit 5c3484
see https://www.gnu.org/licenses/.  */
Packit 5c3484
Packit 5c3484
#include "gmp.h"
Packit 5c3484
#include "gmp-impl.h"
Packit 5c3484
Packit 5c3484
int
Packit 5c3484
mpz_invert (mpz_ptr inverse, mpz_srcptr x, mpz_srcptr n)
Packit 5c3484
{
Packit 5c3484
  mpz_t gcd, tmp;
Packit 5c3484
  mp_size_t xsize, nsize, size;
Packit 5c3484
  TMP_DECL;
Packit 5c3484
Packit 5c3484
  xsize = ABSIZ (x);
Packit 5c3484
  nsize = ABSIZ (n);
Packit 5c3484
Packit 5c3484
  size = MAX (xsize, nsize) + 1;
Packit 5c3484
  TMP_MARK;
Packit 5c3484
Packit 5c3484
  MPZ_TMP_INIT (gcd, size);
Packit 5c3484
  MPZ_TMP_INIT (tmp, size);
Packit 5c3484
  mpz_gcdext (gcd, tmp, (mpz_ptr) 0, x, n);
Packit 5c3484
Packit 5c3484
  /* If no inverse existed, return with an indication of that.  */
Packit 5c3484
  if (!MPZ_EQUAL_1_P (gcd))
Packit 5c3484
    {
Packit 5c3484
      TMP_FREE;
Packit 5c3484
      return 0;
Packit 5c3484
    }
Packit 5c3484
Packit 5c3484
  /* Make sure we return a positive inverse.  */
Packit 5c3484
  if (SIZ (tmp) < 0)
Packit 5c3484
    {
Packit 5c3484
      if (SIZ (n) < 0)
Packit 5c3484
	mpz_sub (inverse, tmp, n);
Packit 5c3484
      else
Packit 5c3484
	mpz_add (inverse, tmp, n);
Packit 5c3484
    }
Packit 5c3484
  else
Packit 5c3484
    mpz_set (inverse, tmp);
Packit 5c3484
Packit 5c3484
  TMP_FREE;
Packit 5c3484
  return 1;
Packit 5c3484
}