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 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 General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
13 The GNU MP Library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with the GNU MP Library; see the file COPYING. If not, write to
20 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
28 mpz_sqrtrem (MP_INT *root, MP_INT *rem, const MP_INT *op)
30 mpz_sqrtrem (root, rem, op)
35 #else /* BERKELEY_MP */
38 msqrt (const MP_INT *op, MP_INT *root, MP_INT *rem)
45 #endif /* BERKELEY_MP */
47 mp_size op_size, root_size, rem_size;
48 mp_ptr root_ptr, op_ptr;
49 mp_ptr free_me = NULL;
54 op_size = 1 / (op_size > 0); /* Divide by zero for negative OP. */
56 if (rem->alloc < op_size)
57 _mpz_realloc (rem, op_size);
59 /* The size of the root is accurate after this simple calculation. */
60 root_size = (op_size + 1) / 2;
65 if (root->alloc < root_size)
67 if (root_ptr == op_ptr)
70 free_me_size = root->alloc;
73 (*_mp_free_func) (root_ptr, root->alloc * BYTES_PER_MP_LIMB);
75 root->alloc = root_size;
76 root_ptr = (mp_ptr) (*_mp_allocate_func) (root_size * BYTES_PER_MP_LIMB);
81 /* Make OP not overlap with ROOT. */
82 if (root_ptr == op_ptr)
84 /* ROOT and OP are identical. Allocate temporary space for OP. */
85 op_ptr = (mp_ptr) alloca (op_size * BYTES_PER_MP_LIMB);
86 /* Copy to the temporary space. Hack: Avoid temporary variable
88 MPN_COPY (op_ptr, root_ptr, op_size);
92 rem_size = mpn_sqrt (root_ptr, rem->d, op_ptr, op_size);
94 root->size = root_size;
96 /* Write remainder size last, to enable us to define this function to
97 give only the square root remainder, if the user calles if with
102 (*_mp_free_func) (free_me, free_me_size * BYTES_PER_MP_LIMB);