1 /* __gmpfr_isqrt && __gmpfr_cuberoot -- Integer square root and cube root
3 Copyright 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
4 Contributed by the Arenaire and Cacao 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 2.1 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.LIB. If not, write to
20 the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,
21 MA 02110-1301, USA. */
23 #include "mpfr-impl.h"
25 /* returns floor(sqrt(n)) */
27 __gmpfr_isqrt (unsigned long n
)
31 /* First find an approximation to floor(sqrt(n)) of the form 2^k. */
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. */
53 /* returns floor(n^(1/3)) */
55 __gmpfr_cuberoot (unsigned long n
)
59 /* First find an approximation to floor(cbrt(n)) of the form 2^k. */
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). */
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))));