1
1
/* mpf_sqrt_ui -- Compute the square root of an unsigned integer.
3
Copyright 1993, 1994, 1996, 2000, 2001 Free Software Foundation, Inc.
3
Copyright 1993, 1994, 1996, 2000, 2001, 2004, 2005 Free Software Foundation,
5
6
This file is part of the GNU MP Library.
17
18
You should have received a copy of the GNU Lesser General Public License
18
19
along with the GNU MP Library; see the file COPYING.LIB. If not, write to
19
the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20
MA 02111-1307, USA. */
20
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21
MA 02110-1301, USA. */
22
23
#include <stdio.h> /* for NULL */
24
25
#include "gmp-impl.h"
28
/* As usual the aim is to produce PREC(r) limbs of result with the high limb
29
non-zero. That high limb will end up floor(sqrt(u)), and limbs below are
30
produced by padding the input with zeros, two for each desired result
31
limb, being 2*(prec-1) for a total 2*prec-1 limbs passed to mpn_sqrtrem.
32
The way mpn_sqrtrem calculates floor(sqrt(x)) ensures the root is correct
33
to the intended accuracy, ie. truncated to prec limbs.
35
With nails, u might be two limbs, in which case a total 2*prec limbs is
36
passed to mpn_sqrtrem (still giving a prec limb result). If uhigh is
37
zero we adjust back to 2*prec-1, since mpn_sqrtrem requires the high
38
non-zero. 2*prec limbs are always allocated, even when uhigh is zero, so
39
the store of uhigh can be done without a conditional.
41
u==0 is a special case so the rest of the code can assume the result is
42
non-zero (ie. will have a non-zero high limb on the result).
46
No attempt is made to identify perfect squares. It's considered this can
47
be left to an application if it might occur with any frequency. As it
48
stands, mpn_sqrtrem does its normal amount of work on a perfect square
49
followed by zero limbs, though of course only an mpn_sqrtrem1 would be
50
actually needed. We also end up leaving our mpf result with lots of low
51
trailing zeros, slowing down subsequent operations.
53
We're not aware of any optimizations that can be made using the fact the
54
input has lots of trailing zeros (apart from the perfect square
58
/* 1 if we (might) need two limbs for u */
59
#define U2 (GMP_NUMB_BITS < BITS_PER_ULONG)
27
62
mpf_sqrt_ui (mpf_ptr r, unsigned long int u)
64
mp_size_t rsize, zeros;
69
if (UNLIKELY (u == 0))
43
78
prec = r->_mp_prec;
80
rsize = zeros + 1 + U2;
46
82
tp = (mp_ptr) TMP_ALLOC (rsize * BYTES_PER_MP_LIMB);
48
MPN_ZERO (tp, rsize - 1);
85
tp[zeros] = u & GMP_NUMB_MASK;
89
mp_limb_t uhigh = u >> GMP_NUMB_BITS;
90
tp[zeros + 1] = uhigh;
91
rsize -= (uhigh == 0);
51
95
mpn_sqrtrem (r->_mp_d, NULL, tp, rsize);
53
r->_mp_size = prec + 1;