beta-0.89.2
[luatex.git] / source / libs / mpfr / mpfr-3.1.3 / src / isqrt.c
blob86910e8a538b163872fc260fdcdee9be6141484f
1 /* __gmpfr_isqrt && __gmpfr_cuberoot -- Integer square root and cube root
3 Copyright 2004-2015 Free Software Foundation, Inc.
4 Contributed by the AriC and Caramel projects, INRIA.
6 This file is part of the GNU MPFR Library.
8 The GNU MPFR Library is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 3 of the License, or (at your
11 option) any later version.
13 The GNU MPFR 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 Lesser General Public
16 License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see
20 http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
21 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */
23 #include "mpfr-impl.h"
25 /* returns floor(sqrt(n)) */
26 unsigned long
27 __gmpfr_isqrt (unsigned long n)
29 unsigned long i, s;
31 /* First find an approximation to floor(sqrt(n)) of the form 2^k. */
32 i = n;
33 s = 1;
34 while (i >= 2)
36 i >>= 2;
37 s <<= 1;
42 s = (s + n / s) / 2;
44 while (!(s*s <= n && (s*s > s*(s+2) || n <= s*(s+2))));
45 /* Short explanation: As mathematically s*(s+2) < 2*ULONG_MAX,
46 the condition s*s > s*(s+2) is evaluated as true when s*(s+2)
47 "overflows" but not s*s. This implies that mathematically, one
48 has s*s <= n <= s*(s+2). If s*s "overflows", this means that n
49 is "large" and the inequality n <= s*(s+2) cannot be satisfied. */
50 return s;
53 /* returns floor(n^(1/3)) */
54 unsigned long
55 __gmpfr_cuberoot (unsigned long n)
57 unsigned long i, s;
59 /* First find an approximation to floor(cbrt(n)) of the form 2^k. */
60 i = n;
61 s = 1;
62 while (i >= 4)
64 i >>= 3;
65 s <<= 1;
68 /* Improve the approximation (this is necessary if n is large, so that
69 mathematically (s+1)*(s+1)*(s+1) isn't much larger than ULONG_MAX). */
70 if (n >= 256)
72 s = (2 * s + n / (s * s)) / 3;
73 s = (2 * s + n / (s * s)) / 3;
74 s = (2 * s + n / (s * s)) / 3;
79 s = (2 * s + n / (s * s)) / 3;
81 while (!(s*s*s <= n && (s*s*s > (s+1)*(s+1)*(s+1) ||
82 n < (s+1)*(s+1)*(s+1))));
83 return s;