xref: /netbsd-src/external/lgpl3/gmp/dist/mpn/generic/gcd_11.c (revision 72c7faa4dbb41dbb0238d6b4a109da0d4b236dd4)
1 /* mpn_gcd_11 -- limb greatest common divisor.
2 
3 Copyright 1994, 1996, 2000, 2001, 2009, 2012, 2019 Free Software Foundation,
4 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 either:
10 
11   * the GNU Lesser General Public License as published by the Free
12     Software Foundation; either version 3 of the License, or (at your
13     option) any later version.
14 
15 or
16 
17   * the GNU General Public License as published by the Free Software
18     Foundation; either version 2 of the License, or (at your option) any
19     later version.
20 
21 or both in parallel, as here.
22 
23 The GNU MP Library is distributed in the hope that it will be useful, but
24 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
25 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
26 for more details.
27 
28 You should have received copies of the GNU General Public License and the
29 GNU Lesser General Public License along with the GNU MP Library.  If not,
30 see https://www.gnu.org/licenses/.  */
31 
32 #include "gmp-impl.h"
33 #include "longlong.h"
34 
35 mp_limb_t
mpn_gcd_11(mp_limb_t u,mp_limb_t v)36 mpn_gcd_11 (mp_limb_t u, mp_limb_t v)
37 {
38   ASSERT (u & v & 1);
39 
40   /* In this loop, we represent the odd numbers ulimb and vlimb
41      without the redundant least significant one bit. This reduction
42      in size by one bit ensures that the high bit of t, below, is set
43      if and only if vlimb > ulimb. */
44 
45   u >>= 1;
46   v >>= 1;
47 
48   while (u != v)
49     {
50       mp_limb_t t;
51       mp_limb_t vgtu;
52       int c;
53 
54       t = u - v;
55       vgtu = LIMB_HIGHBIT_TO_MASK (t);
56 
57       /* v <-- min (u, v) */
58       v += (vgtu & t);
59 
60       /* u <-- |u - v| */
61       u = (t ^ vgtu) - vgtu;
62 
63       count_trailing_zeros (c, t);
64       /* We have c <= GMP_LIMB_BITS - 2 here, so that
65 
66 	   ulimb >>= (c + 1);
67 
68 	 would be safe. But unlike the addition c + 1, a separate
69 	 shift by 1 is independent of c, and can be executed in
70 	 parallel with count_trailing_zeros. */
71       u = (u >> 1) >> c;
72     }
73   return (u << 1) + 1;
74 }
75