/src/gmp-6.2.1/mpz/gcd_ui.c
Line | Count | Source |
1 | | /* mpz_gcd_ui -- Calculate the greatest common divisor of two integers. |
2 | | |
3 | | Copyright 1994, 1996, 1999-2004, 2015 Free Software Foundation, Inc. |
4 | | |
5 | | This file is part of the GNU MP Library. |
6 | | |
7 | | The GNU MP Library is free software; you can redistribute it and/or modify |
8 | | it under the terms of either: |
9 | | |
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. |
13 | | |
14 | | or |
15 | | |
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. |
19 | | |
20 | | or both in parallel, as here. |
21 | | |
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. |
26 | | |
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/. */ |
30 | | |
31 | | #include <stdio.h> /* for NULL */ |
32 | | #include "gmp-impl.h" |
33 | | |
34 | | unsigned long int |
35 | | mpz_gcd_ui (mpz_ptr w, mpz_srcptr u, unsigned long int v) |
36 | 30 | { |
37 | 30 | mp_size_t un; |
38 | 30 | mp_limb_t res; |
39 | | |
40 | | #if BITS_PER_ULONG > GMP_NUMB_BITS /* avoid warnings about shift amount */ |
41 | | if (v > GMP_NUMB_MAX) |
42 | | { |
43 | | mpz_t vz; |
44 | | mp_limb_t vlimbs[2]; |
45 | | vlimbs[0] = v & GMP_NUMB_MASK; |
46 | | vlimbs[1] = v >> GMP_NUMB_BITS; |
47 | | PTR(vz) = vlimbs; |
48 | | SIZ(vz) = 2; |
49 | | mpz_gcd (w, u, vz); |
50 | | /* because v!=0 we will have w<=v hence fitting a ulong */ |
51 | | ASSERT (mpz_fits_ulong_p (w)); |
52 | | return mpz_get_ui (w); |
53 | | } |
54 | | #endif |
55 | | |
56 | 30 | un = ABSIZ(u); |
57 | | |
58 | 30 | if (un == 0) |
59 | 2 | res = v; |
60 | 28 | else if (v == 0) |
61 | 5 | { |
62 | 5 | if (w != NULL) |
63 | 5 | { |
64 | 5 | if (u != w) |
65 | 4 | { |
66 | 4 | MPZ_NEWALLOC (w, un); |
67 | 4 | MPN_COPY (PTR(w), PTR(u), un); |
68 | 4 | } |
69 | 5 | SIZ(w) = un; |
70 | 5 | } |
71 | | /* Return u if it fits a ulong, otherwise 0. */ |
72 | 5 | res = PTR(u)[0]; |
73 | 5 | return (un == 1 && res <= ULONG_MAX ? res : 0); |
74 | 5 | } |
75 | 23 | else |
76 | 23 | res = mpn_gcd_1 (PTR(u), un, (mp_limb_t) v); |
77 | | |
78 | 25 | if (w != NULL) |
79 | 25 | { |
80 | 25 | MPZ_NEWALLOC (w, 1)[0] = res; |
81 | 25 | SIZ(w) = res != 0; |
82 | 25 | } |
83 | 25 | return res; |
84 | 30 | } |