1 /* mpz_gcdext(g, s, t, a, b) -- Set G to gcd(a, b), and S and T such that
4 Copyright (C) 1991, 1993, 1994, 1995, 1996, 1997, 2000 Free Software
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 the GNU Lesser General Public License as published by
11 the Free Software Foundation; either version 2.1 of the License, or (at your
12 option) any later version.
14 The GNU MP Library is distributed in the hope that it will be useful, but
15 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
17 License for more details.
19 You should have received a copy of the GNU Lesser General Public License
20 along with the GNU MP Library; see the file COPYING.LIB. If not, write to
21 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
22 MA 02111-1307, USA. */
24 #include <stdio.h> /* for NULL */
30 mpz_gcdext (mpz_ptr g, mpz_ptr s, mpz_ptr t, mpz_srcptr a, mpz_srcptr b)
32 mpz_gcdext (g, s, t, a, b)
40 mp_size_t asize, bsize, usize, vsize;
43 mp_size_t gsize, ssize, tmp_ssize;
44 mp_ptr gp, sp, tmp_gp, tmp_sp;
47 __mpz_struct stmp, gtmp;
52 /* mpn_gcdext requires that U >= V. Therefore, we often have to swap U and
53 V. This in turn leads to a lot of complications. The computed cofactor
54 will be the wrong one, so we have to fix that up at the end. */
56 asize = ABS (SIZ (a));
57 bsize = ABS (SIZ (b));
60 if (asize > bsize || (asize == bsize && mpn_cmp (ap, bp, asize) > 0))
64 up = (mp_ptr) TMP_ALLOC ((usize + 1) * BYTES_PER_MP_LIMB);
65 vp = (mp_ptr) TMP_ALLOC ((vsize + 1) * BYTES_PER_MP_LIMB);
66 MPN_COPY (up, ap, usize);
67 MPN_COPY (vp, bp, vsize);
77 up = (mp_ptr) TMP_ALLOC ((usize + 1) * BYTES_PER_MP_LIMB);
78 vp = (mp_ptr) TMP_ALLOC ((vsize + 1) * BYTES_PER_MP_LIMB);
79 MPN_COPY (up, bp, usize);
80 MPN_COPY (vp, ap, vsize);
87 tmp_gp = (mp_ptr) TMP_ALLOC ((usize + 1) * BYTES_PER_MP_LIMB);
88 tmp_sp = (mp_ptr) TMP_ALLOC ((usize + 1) * BYTES_PER_MP_LIMB);
94 MPN_COPY (tmp_gp, up, usize);
98 gsize = mpn_gcdext (tmp_gp, tmp_sp, &tmp_ssize, up, usize, vp, vsize);
99 ssize = ABS (tmp_ssize);
101 PTR (>mp) = tmp_gp;
104 PTR (&stmp) = tmp_sp;
105 SIZ (&stmp) = (tmp_ssize ^ SIZ (u)) >= 0 ? ssize : -ssize;
114 MPZ_TMP_INIT (x, ssize + usize + 1);
115 mpz_mul (x, &stmp, u);
116 mpz_sub (x, >mp, x);
117 mpz_tdiv_q (tt, x, v);
123 if (ALLOC (ss) < ssize)
124 _mpz_realloc (ss, ssize);
126 MPN_COPY (sp, tmp_sp, ssize);
127 SIZ (ss) = SIZ (&stmp);
130 if (ALLOC (g) < gsize)
131 _mpz_realloc (g, gsize);
133 MPN_COPY (gp, tmp_gp, gsize);