Austin Schuh | bb1338c | 2024-06-15 19:31:16 -0700 | [diff] [blame] | 1 | /* mpz_tdiv_q -- divide two integers and produce a quotient. |
| 2 | |
| 3 | Copyright 1991, 1993, 1994, 1996, 2000, 2001, 2005, 2010, 2012 Free Software |
| 4 | Foundation, 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 | void |
| 36 | mpz_tdiv_q (mpz_ptr quot, mpz_srcptr num, mpz_srcptr den) |
| 37 | { |
| 38 | mp_size_t ql; |
| 39 | mp_size_t ns, ds, nl, dl; |
| 40 | mp_ptr np, dp, qp, tp; |
| 41 | TMP_DECL; |
| 42 | |
| 43 | ns = SIZ (num); |
| 44 | ds = SIZ (den); |
| 45 | nl = ABS (ns); |
| 46 | dl = ABS (ds); |
| 47 | ql = nl - dl + 1; |
| 48 | |
| 49 | if (UNLIKELY (dl == 0)) |
| 50 | DIVIDE_BY_ZERO; |
| 51 | |
| 52 | if (ql <= 0) |
| 53 | { |
| 54 | SIZ (quot) = 0; |
| 55 | return; |
| 56 | } |
| 57 | |
| 58 | qp = MPZ_REALLOC (quot, ql); |
| 59 | |
| 60 | TMP_MARK; |
| 61 | dp = PTR (den); |
| 62 | |
| 63 | /* Copy denominator to temporary space if it overlaps with the quotient. */ |
| 64 | if (dp == qp) |
| 65 | { |
| 66 | mp_ptr tp; |
| 67 | tp = TMP_ALLOC_LIMBS (dl); |
| 68 | MPN_COPY (tp, dp, dl); |
| 69 | dp = tp; |
| 70 | } |
| 71 | |
| 72 | tp = TMP_ALLOC_LIMBS (nl + 1); |
| 73 | np = PTR (num); |
| 74 | /* Copy numerator to temporary space if it overlaps with the quotient. */ |
| 75 | if (np == qp) |
| 76 | { |
| 77 | MPN_COPY (tp, np, nl); |
| 78 | /* Overlap dividend and scratch. */ |
| 79 | np = tp; |
| 80 | } |
| 81 | mpn_div_q (qp, np, nl, dp, dl, tp); |
| 82 | |
| 83 | ql -= qp[ql - 1] == 0; |
| 84 | |
| 85 | SIZ (quot) = (ns ^ ds) >= 0 ? ql : -ql; |
| 86 | TMP_FREE; |
| 87 | } |