blob: 4618599d8ff949bf4a0955f35e660df9f2d20499 [file] [log] [blame]
Austin Schuhdace2a62020-08-18 10:56:48 -07001/* mpz_tdiv_ui(dividend, divisor_limb) -- Return DIVDEND mod DIVISOR_LIMB.
2
3Copyright 1991, 1993, 1994, 1996-1998, 2001, 2002, 2004, 2005, 2012 Free
4Software Foundation, Inc.
5
6This file is part of the GNU MP Library.
7
8The GNU MP Library is free software; you can redistribute it and/or modify
9it 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
15or
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
21or both in parallel, as here.
22
23The GNU MP Library is distributed in the hope that it will be useful, but
24WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
25or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
26for more details.
27
28You should have received copies of the GNU General Public License and the
29GNU Lesser General Public License along with the GNU MP Library. If not,
30see https://www.gnu.org/licenses/. */
31
32#include "gmp-impl.h"
33#include "longlong.h"
34
35unsigned long int
36mpz_tdiv_ui (mpz_srcptr dividend, unsigned long int divisor)
37{
38 mp_size_t ns, nn;
39 mp_ptr np;
40 mp_limb_t rl;
41
42 if (UNLIKELY (divisor == 0))
43 DIVIDE_BY_ZERO;
44
45 ns = SIZ(dividend);
46 if (ns == 0)
47 {
48 return 0;
49 }
50
51 nn = ABS(ns);
52 np = PTR(dividend);
53
54#if BITS_PER_ULONG > GMP_NUMB_BITS /* avoid warnings about shift amount */
55 if (divisor > GMP_NUMB_MAX)
56 {
57 mp_limb_t dp[2], rp[2];
58 mp_ptr qp;
59 mp_size_t rn;
60 TMP_DECL;
61
62 if (nn == 1) /* tdiv_qr requirements; tested above for 0 */
63 {
64 rl = np[0];
65 return rl;
66 }
67
68 TMP_MARK;
69 dp[0] = divisor & GMP_NUMB_MASK;
70 dp[1] = divisor >> GMP_NUMB_BITS;
71 qp = TMP_ALLOC_LIMBS (nn - 2 + 1);
72 mpn_tdiv_qr (qp, rp, (mp_size_t) 0, np, nn, dp, (mp_size_t) 2);
73 TMP_FREE;
74 rl = rp[0] + (rp[1] << GMP_NUMB_BITS);
75 rn = 2 - (rp[1] == 0); rn -= (rp[rn - 1] == 0);
76 }
77 else
78#endif
79 {
80 rl = mpn_mod_1 (np, nn, (mp_limb_t) divisor);
81 }
82
83 return rl;
84}