Austin Schuh | bb1338c | 2024-06-15 19:31:16 -0700 | [diff] [blame] | 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 | { |
| 37 | mp_size_t un; |
| 38 | 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 | un = ABSIZ(u); |
| 57 | |
| 58 | if (un == 0) |
| 59 | res = v; |
| 60 | else if (v == 0) |
| 61 | { |
| 62 | if (w != NULL) |
| 63 | { |
| 64 | if (u != w) |
| 65 | { |
| 66 | MPZ_NEWALLOC (w, un); |
| 67 | MPN_COPY (PTR(w), PTR(u), un); |
| 68 | } |
| 69 | SIZ(w) = un; |
| 70 | } |
| 71 | /* Return u if it fits a ulong, otherwise 0. */ |
| 72 | res = PTR(u)[0]; |
| 73 | return (un == 1 && res <= ULONG_MAX ? res : 0); |
| 74 | } |
| 75 | else |
| 76 | res = mpn_gcd_1 (PTR(u), un, (mp_limb_t) v); |
| 77 | |
| 78 | if (w != NULL) |
| 79 | { |
| 80 | MPZ_NEWALLOC (w, 1)[0] = res; |
| 81 | SIZ(w) = res != 0; |
| 82 | } |
| 83 | return res; |
| 84 | } |