beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpz / invert.c
blob09cdd9a121a5988d05ef32cdeec22bdba10006cc
1 /* mpz_invert (inv, x, n). Find multiplicative inverse of X in Z(N).
2 If X has an inverse, return non-zero and store inverse in INVERSE,
3 otherwise, return 0 and put garbage in INVERSE.
5 Copyright 1996-2001, 2005, 2012, 2014 Free Software Foundation, Inc.
7 This file is part of the GNU MP Library.
9 The GNU MP Library is free software; you can redistribute it and/or modify
10 it under the terms of either:
12 * the GNU Lesser General Public License as published by the Free
13 Software Foundation; either version 3 of the License, or (at your
14 option) any later version.
18 * the GNU General Public License as published by the Free Software
19 Foundation; either version 2 of the License, or (at your option) any
20 later version.
22 or both in parallel, as here.
24 The GNU MP Library is distributed in the hope that it will be useful, but
25 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
26 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
27 for more details.
29 You should have received copies of the GNU General Public License and the
30 GNU Lesser General Public License along with the GNU MP Library. If not,
31 see https://www.gnu.org/licenses/. */
33 #include "gmp.h"
34 #include "gmp-impl.h"
36 int
37 mpz_invert (mpz_ptr inverse, mpz_srcptr x, mpz_srcptr n)
39 mpz_t gcd, tmp;
40 mp_size_t xsize, nsize, size;
41 TMP_DECL;
43 xsize = ABSIZ (x);
44 nsize = ABSIZ (n);
46 size = MAX (xsize, nsize) + 1;
47 TMP_MARK;
49 MPZ_TMP_INIT (gcd, size);
50 MPZ_TMP_INIT (tmp, size);
51 mpz_gcdext (gcd, tmp, (mpz_ptr) 0, x, n);
53 /* If no inverse existed, return with an indication of that. */
54 if (!MPZ_EQUAL_1_P (gcd))
56 TMP_FREE;
57 return 0;
60 /* Make sure we return a positive inverse. */
61 if (SIZ (tmp) < 0)
63 if (SIZ (n) < 0)
64 mpz_sub (inverse, tmp, n);
65 else
66 mpz_add (inverse, tmp, n);
68 else
69 mpz_set (inverse, tmp);
71 TMP_FREE;
72 return 1;