1 /* mpz_sqrtrem(root,rem,x) -- Set ROOT to floor(sqrt(X)) and REM
2 to the remainder, i.e. X - ROOT**2.
4 Copyright 1991, 1993, 1994, 1996, 2000, 2001, 2005 Free Software Foundation,
7 This file is part of the GNU MP Library.
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.
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.
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/. */
22 #include <stdio.h> /* for NULL */
31 mpz_sqrtrem (mpz_ptr root, mpz_ptr rem, mpz_srcptr op)
32 #else /* BERKELEY_MP */
33 msqrt (mpz_srcptr op, mpz_ptr root, mpz_ptr rem)
34 #endif /* BERKELEY_MP */
36 mp_size_t op_size, root_size, rem_size;
37 mp_ptr root_ptr, op_ptr;
38 mp_ptr free_me = NULL;
39 mp_size_t free_me_size;
43 op_size = op->_mp_size;
53 if (rem->_mp_alloc < op_size)
54 _mpz_realloc (rem, op_size);
56 /* The size of the root is accurate after this simple calculation. */
57 root_size = (op_size + 1) / 2;
59 root_ptr = root->_mp_d;
62 if (root->_mp_alloc < root_size)
64 if (root_ptr == op_ptr)
67 free_me_size = root->_mp_alloc;
70 (*__gmp_free_func) (root_ptr, root->_mp_alloc * BYTES_PER_MP_LIMB);
72 root->_mp_alloc = root_size;
73 root_ptr = (mp_ptr) (*__gmp_allocate_func) (root_size * BYTES_PER_MP_LIMB);
74 root->_mp_d = root_ptr;
78 /* Make OP not overlap with ROOT. */
79 if (root_ptr == op_ptr)
81 /* ROOT and OP are identical. Allocate temporary space for OP. */
82 op_ptr = (mp_ptr) TMP_ALLOC (op_size * BYTES_PER_MP_LIMB);
83 /* Copy to the temporary space. Hack: Avoid temporary variable
85 MPN_COPY (op_ptr, root_ptr, op_size);
89 rem_size = mpn_sqrtrem (root_ptr, rem->_mp_d, op_ptr, op_size);
91 root->_mp_size = root_size;
93 /* Write remainder size last, to enable us to define this function to
94 give only the square root remainder, if the user calls if with
96 rem->_mp_size = rem_size;
99 (*__gmp_free_func) (free_me, free_me_size * BYTES_PER_MP_LIMB);