1 /* mpn_mod_1s_1p (ap, n, b, cps) 2 Divide (ap,,n) by b. Return the single-limb remainder. 3 Requires that b < B / 2. 4 5 Contributed to the GNU project by Torbjorn Granlund. 6 7 THE FUNCTIONS IN THIS FILE ARE INTERNAL WITH MUTABLE INTERFACES. IT IS ONLY 8 SAFE TO REACH THEM THROUGH DOCUMENTED INTERFACES. IN FACT, IT IS ALMOST 9 GUARANTEED THAT THEY WILL CHANGE OR DISAPPEAR IN A FUTURE GNU MP RELEASE. 10 11 Copyright 2008, 2009 Free Software Foundation, Inc. 12 13 This file is part of the GNU MP Library. 14 15 The GNU MP Library is free software; you can redistribute it and/or modify 16 it under the terms of the GNU Lesser General Public License as published by 17 the Free Software Foundation; either version 3 of the License, or (at your 18 option) any later version. 19 20 The GNU MP Library is distributed in the hope that it will be useful, but 21 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 22 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 23 License for more details. 24 25 You should have received a copy of the GNU Lesser General Public License 26 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ 27 28 #include "gmp.h" 29 #include "gmp-impl.h" 30 #include "longlong.h" 31 32 void 33 mpn_mod_1s_1p_cps (mp_limb_t cps[4], mp_limb_t b) 34 { 35 mp_limb_t bi; 36 mp_limb_t B1modb, B2modb; 37 int cnt; 38 39 ASSERT (b <= GMP_NUMB_MAX / 2); 40 41 count_leading_zeros (cnt, b); 42 43 b <<= cnt; 44 invert_limb (bi, b); 45 46 B1modb = -b * ((bi >> (GMP_LIMB_BITS-cnt)) | (CNST_LIMB(1) << cnt)); 47 ASSERT (B1modb <= b); /* NB: not fully reduced mod b */ 48 udiv_rnd_preinv (B2modb, B1modb, b, bi); 49 50 B1modb >>= cnt; 51 B2modb >>= cnt; 52 53 cps[0] = bi; 54 cps[1] = cnt; 55 cps[2] = B1modb; 56 cps[3] = B2modb; 57 } 58 59 mp_limb_t 60 mpn_mod_1s_1p (mp_srcptr ap, mp_size_t n, mp_limb_t b, mp_limb_t bmodb[4]) 61 { 62 mp_limb_t rh, rl, bi, q, ph, pl, r; 63 mp_limb_t B1modb, B2modb; 64 mp_size_t i; 65 int cnt; 66 67 B1modb = bmodb[2]; 68 B2modb = bmodb[3]; 69 70 umul_ppmm (ph, pl, ap[n - 1], B1modb); 71 add_ssaaaa (rh, rl, ph, pl, 0, ap[n - 2]); 72 73 for (i = n - 3; i >= 0; i -= 1) 74 { 75 /* rr = ap[i] < B 76 + LO(rr) * (B mod b) <= (B-1)(b-1) 77 + HI(rr) * (B^2 mod b) <= (B-1)(b-1) 78 */ 79 umul_ppmm (ph, pl, rl, B1modb); 80 add_ssaaaa (ph, pl, ph, pl, 0, ap[i]); 81 82 umul_ppmm (rh, rl, rh, B2modb); 83 add_ssaaaa (rh, rl, rh, rl, ph, pl); 84 } 85 86 bi = bmodb[0]; 87 cnt = bmodb[1]; 88 #if 1 89 { 90 mp_limb_t mask; 91 r = (rh << cnt) | (rl >> (GMP_LIMB_BITS - cnt)); 92 mask = -(mp_limb_t) (r >= b); 93 r -= mask & b; 94 } 95 #else 96 udiv_qrnnd_preinv (q, r, rh >> (GMP_LIMB_BITS - cnt), 97 (rh << cnt) | (rl >> (GMP_LIMB_BITS - cnt)), b, bi); 98 ASSERT (q <= 1); /* optimize for small quotient? */ 99 #endif 100 101 udiv_qrnnd_preinv (q, r, r, rl << cnt, b, bi); 102 103 return r >> cnt; 104 } 105