1 /* mpz_sqrtrem(root,rem,x) -- Set ROOT to floor(sqrt(X)) and REM 2 to the remainder, i.e. X - ROOT**2. 3 4 Copyright 1991, 1993, 1994, 1996, 2000, 2001, 2005, 2011, 2012 Free Software 5 Foundation, Inc. 6 7 This file is part of the GNU MP Library. 8 9 The GNU MP Library is free software; you can redistribute it and/or modify 10 it under the terms of the GNU Lesser General Public License as published by 11 the Free Software Foundation; either version 3 of the License, or (at your 12 option) any later version. 13 14 The GNU MP Library is distributed in the hope that it will be useful, but 15 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 16 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 17 License for more details. 18 19 You should have received a copy of the GNU Lesser General Public License 20 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ 21 22 #include "gmp.h" 23 #include "gmp-impl.h" 24 25 void 26 mpz_sqrtrem (mpz_ptr root, mpz_ptr rem, mpz_srcptr op) 27 { 28 mp_size_t op_size, root_size, rem_size; 29 mp_ptr root_ptr, op_ptr, rem_ptr; 30 31 op_size = SIZ (op); 32 if (UNLIKELY (op_size <= 0)) 33 { 34 if (op_size < 0) 35 SQRT_OF_NEGATIVE; 36 SIZ(root) = 0; 37 SIZ(rem) = 0; 38 return; 39 } 40 41 rem_ptr = MPZ_REALLOC (rem, op_size); 42 43 /* The size of the root is accurate after this simple calculation. */ 44 root_size = (op_size + 1) / 2; 45 SIZ (root) = root_size; 46 47 op_ptr = PTR (op); 48 49 if (root == op) 50 { 51 /* Allocate temp space for the root, which we then copy to the 52 shared OP/ROOT variable. */ 53 TMP_DECL; 54 TMP_MARK; 55 56 root_ptr = TMP_ALLOC_LIMBS (root_size); 57 rem_size = mpn_sqrtrem (root_ptr, rem_ptr, op_ptr, op_size); 58 59 if (rem != root) /* Don't overwrite remainder */ 60 MPN_COPY (op_ptr, root_ptr, root_size); 61 62 TMP_FREE; 63 } 64 else 65 { 66 root_ptr = MPZ_REALLOC (root, root_size); 67 68 rem_size = mpn_sqrtrem (root_ptr, rem_ptr, op_ptr, op_size); 69 } 70 71 /* Write remainder size last, to make this function give only the square root 72 remainder, when passed ROOT == REM. */ 73 SIZ (rem) = rem_size; 74 } 75