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 (C) 1991, 1993, 1994, 1996 Free Software Foundation, Inc.
6 This file is part of the GNU MP Library.
8 The GNU MP Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Library General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or (at your
11 option) any later version.
13 The GNU MP Library is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
16 License for more details.
18 You should have received a copy of the GNU Library General Public License
19 along with the GNU MP Library; see the file COPYING.LIB. If not, write to
20 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
21 MA 02111-1307, USA. */
29 mpz_sqrtrem (mpz_ptr root, mpz_ptr rem, mpz_srcptr op)
31 mpz_sqrtrem (root, rem, op)
36 #else /* BERKELEY_MP */
39 msqrt (mpz_srcptr op, mpz_ptr root, mpz_ptr rem)
46 #endif /* BERKELEY_MP */
48 mp_size_t op_size, root_size, rem_size;
49 mp_ptr root_ptr, op_ptr;
50 mp_ptr free_me = NULL;
51 mp_size_t free_me_size;
55 op_size = op->_mp_size;
57 op_size = 1 / (op_size > 0); /* Divide by zero for negative OP. */
59 if (rem->_mp_alloc < op_size)
60 _mpz_realloc (rem, op_size);
62 /* The size of the root is accurate after this simple calculation. */
63 root_size = (op_size + 1) / 2;
65 root_ptr = root->_mp_d;
68 if (root->_mp_alloc < root_size)
70 if (root_ptr == op_ptr)
73 free_me_size = root->_mp_alloc;
76 (*_mp_free_func) (root_ptr, root->_mp_alloc * BYTES_PER_MP_LIMB);
78 root->_mp_alloc = root_size;
79 root_ptr = (mp_ptr) (*_mp_allocate_func) (root_size * BYTES_PER_MP_LIMB);
80 root->_mp_d = root_ptr;
84 /* Make OP not overlap with ROOT. */
85 if (root_ptr == op_ptr)
87 /* ROOT and OP are identical. Allocate temporary space for OP. */
88 op_ptr = (mp_ptr) TMP_ALLOC (op_size * BYTES_PER_MP_LIMB);
89 /* Copy to the temporary space. Hack: Avoid temporary variable
91 MPN_COPY (op_ptr, root_ptr, op_size);
95 rem_size = mpn_sqrtrem (root_ptr, rem->_mp_d, op_ptr, op_size);
97 root->_mp_size = root_size;
99 /* Write remainder size last, to enable us to define this function to
100 give only the square root remainder, if the user calls if with
102 rem->_mp_size = rem_size;
105 (*_mp_free_func) (free_me, free_me_size * BYTES_PER_MP_LIMB);