1 /* mpz_sqrt(root, u) -- Set ROOT to floor(sqrt(U)).
3 Copyright (C) 1991 Free Software Foundation, Inc.
5 This file is part of the GNU MP Library.
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 The GNU MP Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with the GNU MP Library; see the file COPYING. If not, write to
19 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
21 /* This code is just correct if "unsigned char" has at least 8 bits. It
22 doesn't help to use CHAR_BIT from limits.h, as the real problem is
30 mpz_sqrt (MP_INT *root, const MP_INT *op)
37 mp_size op_size, root_size;
38 mp_ptr root_ptr, op_ptr;
39 mp_ptr free_me = NULL;
44 op_size = 1 / op_size > 0; /* Divide by zero for negative OP. */
46 /* The size of the root is accurate after this simple calculation. */
47 root_size = (op_size + 1) / 2;
52 if (root->alloc < root_size)
54 if (root_ptr == op_ptr)
57 free_me_size = root->alloc;
60 (*_mp_free_func) (root_ptr, root->alloc * BYTES_PER_MP_LIMB);
62 root->alloc = root_size;
63 root_ptr = (mp_ptr) (*_mp_allocate_func) (root_size * BYTES_PER_MP_LIMB);
68 /* Make OP not overlap with ROOT. */
69 if (root_ptr == op_ptr)
71 /* ROOT and OP are identical. Allocate temporary space for OP. */
72 op_ptr = (mp_ptr) alloca (op_size * BYTES_PER_MP_LIMB);
73 /* Copy to the temporary space. Hack: Avoid temporary variable
75 MPN_COPY (op_ptr, root_ptr, op_size);
79 mpn_sqrt (root_ptr, NULL, op_ptr, op_size);
81 root->size = root_size;
84 (*_mp_free_func) (free_me, free_me_size * BYTES_PER_MP_LIMB);