xref: /dragonfly/contrib/gmp/mpn/generic/gcdext_1.c (revision fcf53d9b)
1 /* mpn_gcdext -- Extended Greatest Common Divisor.
2 
3 Copyright 1996, 1998, 2000, 2001, 2002, 2003, 2004, 2005, 2008, 2009 Free Software
4 Foundation, Inc.
5 
6 This file is part of the GNU MP Library.
7 
8 The GNU MP Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or (at your
11 option) any later version.
12 
13 The GNU MP Library is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
16 License for more details.
17 
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
20 
21 #include "gmp.h"
22 #include "gmp-impl.h"
23 #include "longlong.h"
24 
25 
26 /* FIXME: Takes two single-word limbs. It could be extended to a
27  * function that accepts a bignum for the first input, and only
28  * returns the first co-factor. */
29 
30 mp_limb_t
31 mpn_gcdext_1 (mp_limb_signed_t *up, mp_limb_signed_t *vp,
32 	      mp_limb_t a, mp_limb_t b)
33 {
34   /* Maintain
35 
36      a =  u0 A + v0 B
37      b =  u1 A + v1 B
38 
39      where A, B are the original inputs.
40   */
41   mp_limb_signed_t u0 = 1;
42   mp_limb_signed_t v0 = 0;
43   mp_limb_signed_t u1 = 0;
44   mp_limb_signed_t v1 = 1;
45 
46   ASSERT (a > 0);
47   ASSERT (b > 0);
48 
49   if (a < b)
50     goto divide_by_b;
51 
52   for (;;)
53     {
54       mp_limb_t q;
55 
56       q = a / b;
57       a -= q * b;
58 
59       if (a == 0)
60 	{
61 	  *up = u1;
62 	  *vp = v1;
63 	  return b;
64 	}
65       u0 -= q * u1;
66       v0 -= q * v1;
67 
68     divide_by_b:
69       q = b / a;
70       b -= q * a;
71 
72       if (b == 0)
73 	{
74 	  *up = u0;
75 	  *vp = v0;
76 	  return a;
77 	}
78       u1 -= q * u0;
79       v1 -= q * v0;
80     }
81 }
82