beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpz / tdiv_qr_ui.c
blob4f667abe07d9320649f7babc3a201cb37a861bcb
1 /* mpz_tdiv_qr_ui(quot,rem,dividend,short_divisor) --
2 Set QUOT to DIVIDEND / SHORT_DIVISOR
3 and REM to DIVIDEND mod SHORT_DIVISOR.
5 Copyright 1991, 1993, 1994, 1996, 1998, 2001, 2002, 2004, 2012 Free Software
6 Foundation, Inc.
8 This file is part of the GNU MP Library.
10 The GNU MP Library is free software; you can redistribute it and/or modify
11 it under the terms of either:
13 * the GNU Lesser General Public License as published by the Free
14 Software Foundation; either version 3 of the License, or (at your
15 option) any later version.
19 * the GNU General Public License as published by the Free Software
20 Foundation; either version 2 of the License, or (at your option) any
21 later version.
23 or both in parallel, as here.
25 The GNU MP Library is distributed in the hope that it will be useful, but
26 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
27 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
28 for more details.
30 You should have received copies of the GNU General Public License and the
31 GNU Lesser General Public License along with the GNU MP Library. If not,
32 see https://www.gnu.org/licenses/. */
34 #include "gmp.h"
35 #include "gmp-impl.h"
37 unsigned long int
38 mpz_tdiv_qr_ui (mpz_ptr quot, mpz_ptr rem, mpz_srcptr dividend, unsigned long int divisor)
40 mp_size_t ns, nn, qn;
41 mp_ptr np, qp;
42 mp_limb_t rl;
44 if (UNLIKELY (divisor == 0))
45 DIVIDE_BY_ZERO;
47 ns = SIZ(dividend);
48 if (ns == 0)
50 SIZ(quot) = 0;
51 SIZ(rem) = 0;
52 return 0;
55 nn = ABS(ns);
56 qp = MPZ_REALLOC (quot, nn);
57 np = PTR(dividend);
59 #if BITS_PER_ULONG > GMP_NUMB_BITS /* avoid warnings about shift amount */
60 if (divisor > GMP_NUMB_MAX)
62 mp_limb_t dp[2];
63 mp_ptr rp;
64 mp_size_t rn;
66 if (nn == 1) /* tdiv_qr requirements; tested above for 0 */
68 SIZ(quot) = 0;
69 rl = np[0];
70 SIZ(rem) = ns >= 0 ? 1 : -1;
71 PTR(rem)[0] = rl;
72 return rl;
75 rp = MPZ_REALLOC (rem, 2);
77 dp[0] = divisor & GMP_NUMB_MASK;
78 dp[1] = divisor >> GMP_NUMB_BITS;
79 mpn_tdiv_qr (qp, rp, (mp_size_t) 0, np, nn, dp, (mp_size_t) 2);
80 rl = rp[0] + (rp[1] << GMP_NUMB_BITS);
81 qn = nn - 2 + 1; qn -= qp[qn - 1] == 0; qn -= qn != 0 && qp[qn - 1] == 0;
82 rn = 2 - (rp[1] == 0); rn -= (rp[rn - 1] == 0);
83 SIZ(rem) = ns >= 0 ? rn : -rn;
85 else
86 #endif
88 rl = mpn_divrem_1 (qp, (mp_size_t) 0, np, nn, (mp_limb_t) divisor);
89 if (rl == 0)
90 SIZ(rem) = 0;
91 else
93 /* Store the single-limb remainder. We don't check if there's space
94 for just one limb, since no function ever makes zero space. */
95 SIZ(rem) = ns >= 0 ? 1 : -1;
96 PTR(rem)[0] = rl;
98 qn = nn - (qp[nn - 1] == 0);
101 SIZ(quot) = ns >= 0 ? qn : -qn;
102 return rl;