beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpz / gcd_ui.c
blobe26d03f64a910b3ed0f44b1c3abb55fc7b54a0d1
1 /* mpz_gcd_ui -- Calculate the greatest common divisor of two integers.
3 Copyright 1994, 1996, 1999-2004 Free Software Foundation, Inc.
5 This file is part of the GNU MP Library.
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of either:
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
16 * the GNU General Public License as published by the Free Software
17 Foundation; either version 2 of the License, or (at your option) any
18 later version.
20 or both in parallel, as here.
22 The GNU MP Library is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
25 for more details.
27 You should have received copies of the GNU General Public License and the
28 GNU Lesser General Public License along with the GNU MP Library. If not,
29 see https://www.gnu.org/licenses/. */
31 #include <stdio.h> /* for NULL */
32 #include "gmp.h"
33 #include "gmp-impl.h"
35 unsigned long int
36 mpz_gcd_ui (mpz_ptr w, mpz_srcptr u, unsigned long int v)
38 mp_size_t un;
39 mp_limb_t res;
41 #if BITS_PER_ULONG > GMP_NUMB_BITS /* avoid warnings about shift amount */
42 if (v > GMP_NUMB_MAX)
44 mpz_t vz;
45 mp_limb_t vlimbs[2];
46 vlimbs[0] = v & GMP_NUMB_MASK;
47 vlimbs[1] = v >> GMP_NUMB_BITS;
48 PTR(vz) = vlimbs;
49 SIZ(vz) = 2;
50 mpz_gcd (w, u, vz);
51 /* because v!=0 we will have w<=v hence fitting a ulong */
52 ASSERT (mpz_fits_ulong_p (w));
53 return mpz_get_ui (w);
55 #endif
57 un = ABSIZ(u);
59 if (un == 0)
60 res = v;
61 else if (v == 0)
63 if (w != NULL)
65 if (u != w)
67 MPZ_REALLOC (w, un);
68 MPN_COPY (PTR(w), PTR(u), un);
70 SIZ(w) = un;
72 /* Return u if it fits a ulong, otherwise 0. */
73 res = PTR(u)[0];
74 return (un == 1 && res <= ULONG_MAX ? res : 0);
76 else
77 res = mpn_gcd_1 (PTR(u), un, (mp_limb_t) v);
79 if (w != NULL)
81 PTR(w)[0] = res;
82 SIZ(w) = res != 0;
84 return res;