xref: /netbsd-src/external/lgpl3/gmp/dist/mpz/invert.c (revision 6d322f2f4598f0d8a138f10ea648ec4fabe41f8b)
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.
4 
5 Copyright 1996, 1997, 1998, 1999, 2000, 2001, 2005, 2012 Free Software
6 Foundation, Inc.
7 
8 This file is part of the GNU MP Library.
9 
10 The GNU MP Library is free software; you can redistribute it and/or modify
11 it under the terms of the GNU Lesser General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or (at your
13 option) any later version.
14 
15 The GNU MP Library is distributed in the hope that it will be useful, but
16 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
18 License for more details.
19 
20 You should have received a copy of the GNU Lesser General Public License
21 along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
22 
23 #include "gmp.h"
24 #include "gmp-impl.h"
25 
26 int
27 mpz_invert (mpz_ptr inverse, mpz_srcptr x, mpz_srcptr n)
28 {
29   mpz_t gcd, tmp;
30   mp_size_t xsize, nsize, size;
31   TMP_DECL;
32 
33   xsize = ABSIZ (x);
34   nsize = ABSIZ (n);
35 
36   /* No inverse exists if the leftside operand is 0.  Likewise, no
37      inverse exists if the mod operand is 1.  */
38   if (xsize == 0 || (nsize == 1 && (PTR (n))[0] == 1))
39     return 0;
40 
41   size = MAX (xsize, nsize) + 1;
42   TMP_MARK;
43 
44   MPZ_TMP_INIT (gcd, size);
45   MPZ_TMP_INIT (tmp, size);
46   mpz_gcdext (gcd, tmp, (mpz_ptr) 0, x, n);
47 
48   /* If no inverse existed, return with an indication of that.  */
49   if (!MPZ_EQUAL_1_P (gcd))
50     {
51       TMP_FREE;
52       return 0;
53     }
54 
55   /* Make sure we return a positive inverse.  */
56   if (SIZ (tmp) < 0)
57     {
58       if (SIZ (n) < 0)
59 	mpz_sub (inverse, tmp, n);
60       else
61 	mpz_add (inverse, tmp, n);
62     }
63   else
64     mpz_set (inverse, tmp);
65 
66   TMP_FREE;
67   return 1;
68 }
69