1 /* mpn_sbpi1_div_qr -- Schoolbook division using the M�ller-Granlund 3/2 2 division algorithm. 3 4 Contributed to the GNU project by Torbjorn Granlund. 5 6 THE FUNCTION IN THIS FILE IS INTERNAL WITH A MUTABLE INTERFACE. IT IS ONLY 7 SAFE TO REACH IT THROUGH DOCUMENTED INTERFACES. IN FACT, IT IS ALMOST 8 GUARANTEED THAT IT WILL CHANGE OR DISAPPEAR IN A FUTURE GMP RELEASE. 9 10 Copyright 2007, 2009 Free Software Foundation, Inc. 11 12 This file is part of the GNU MP Library. 13 14 The GNU MP Library is free software; you can redistribute it and/or modify 15 it under the terms of the GNU Lesser General Public License as published by 16 the Free Software Foundation; either version 3 of the License, or (at your 17 option) any later version. 18 19 The GNU MP Library is distributed in the hope that it will be useful, but 20 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 21 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 22 License for more details. 23 24 You should have received a copy of the GNU Lesser General Public License 25 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ 26 27 28 #include "gmp.h" 29 #include "gmp-impl.h" 30 #include "longlong.h" 31 32 mp_limb_t 33 mpn_sbpi1_div_qr (mp_ptr qp, 34 mp_ptr np, mp_size_t nn, 35 mp_srcptr dp, mp_size_t dn, 36 mp_limb_t dinv) 37 { 38 mp_limb_t qh; 39 mp_size_t i; 40 mp_limb_t n1, n0; 41 mp_limb_t d1, d0; 42 mp_limb_t cy, cy1; 43 mp_limb_t q; 44 45 ASSERT (dn > 2); 46 ASSERT (nn >= dn); 47 ASSERT ((dp[dn-1] & GMP_NUMB_HIGHBIT) != 0); 48 49 np += nn; 50 51 qh = mpn_cmp (np - dn, dp, dn) >= 0; 52 if (qh != 0) 53 mpn_sub_n (np - dn, np - dn, dp, dn); 54 55 qp += nn - dn; 56 57 dn -= 2; /* offset dn by 2 for main division loops, 58 saving two iterations in mpn_submul_1. */ 59 d1 = dp[dn + 1]; 60 d0 = dp[dn + 0]; 61 62 np -= 2; 63 64 n1 = np[1]; 65 66 for (i = nn - (dn + 2); i > 0; i--) 67 { 68 np--; 69 if (UNLIKELY (n1 == d1) && np[1] == d0) 70 { 71 q = GMP_NUMB_MASK; 72 mpn_submul_1 (np - dn, dp, dn + 2, q); 73 n1 = np[1]; /* update n1, last loop's value will now be invalid */ 74 } 75 else 76 { 77 udiv_qr_3by2 (q, n1, n0, n1, np[1], np[0], d1, d0, dinv); 78 79 cy = mpn_submul_1 (np - dn, dp, dn, q); 80 81 cy1 = n0 < cy; 82 n0 = (n0 - cy) & GMP_NUMB_MASK; 83 cy = n1 < cy1; 84 n1 = (n1 - cy1) & GMP_NUMB_MASK; 85 np[0] = n0; 86 87 if (UNLIKELY (cy != 0)) 88 { 89 n1 += d1 + mpn_add_n (np - dn, np - dn, dp, dn + 1); 90 q--; 91 } 92 } 93 94 *--qp = q; 95 } 96 np[1] = n1; 97 98 return qh; 99 } 100