* regexec.c (group_nodes_into_DFAstates): Fix a buffer overrun
[gnulib.git] / lib / gcd.c
1 /* Arithmetic.
2    Copyright (C) 2001-2002, 2006 Free Software Foundation, Inc.
3    Written by Bruno Haible <bruno@clisp.org>, 2001.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software Foundation,
17    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
18
19 /* This file can also be used to define gcd functions for other unsigned
20    types, such as 'unsigned long long' or 'uintmax_t'.  */
21 #ifndef WORD_T
22 /* Specification.  */
23 # include "gcd.h"
24 # define WORD_T unsigned long
25 # define GCD gcd
26 #endif
27
28 #include <stdlib.h>
29
30 /* Return the greatest common divisor of a > 0 and b > 0.  */
31 WORD_T
32 GCD (WORD_T a, WORD_T b)
33 {
34   /* Why no division, as in Euclid's algorithm? Because in Euclid's algorithm
35      the division result floor(a/b) or floor(b/a) is very often = 1 or = 2,
36      and nearly always < 8.  A sequence of a few subtractions and tests is
37      faster than a division.  */
38   /* Why not Euclid's algorithm? Because the two integers can be shifted by 1
39      bit in a single instruction, and the algorithm uses fewer variables than
40      Euclid's algorithm.  */
41
42   WORD_T c = a | b;
43   c = c ^ (c - 1);
44   /* c = largest power of 2 that divides a and b.  */
45
46   if (a & c)
47     {
48       if (b & c)
49         goto odd_odd;
50       else
51         goto odd_even;
52     }
53   else
54     {
55       if (b & c)
56         goto even_odd;
57       else
58         abort ();
59     }
60
61   for (;;)
62     {
63     odd_odd: /* a/c and b/c both odd */
64       if (a == b)
65         break;
66       if (a > b)
67         {
68           a = a - b;
69         even_odd: /* a/c even, b/c odd */
70           do
71             a = a >> 1;
72           while ((a & c) == 0);
73         }
74       else
75         {
76           b = b - a;
77         odd_even: /* a/c odd, b/c even */
78           do
79             b = b >> 1;
80           while ((b & c) == 0);
81         }
82     }
83
84   /* a = b */
85   return a;
86 }