]> www.ginac.de Git - cln.git/blob - src/base/low/cl_low_isqrt2.cc
* All Files have been modified for inclusion of namespace cln;
[cln.git] / src / base / low / cl_low_isqrt2.cc
1 // isqrt().
2
3 // General includes.
4 #include "cl_sysdep.h"
5
6 // Specification.
7 #include "cl_low.h"
8
9
10 // Implementation.
11
12 namespace cln {
13
14 // Zieht die Ganzzahl-Wurzel aus einer 64-Bit-Zahl und
15 // liefert eine 32-Bit-Wurzel.
16 // isqrt(x1,x0)
17 // > uintL2 x = x1*2^32+x0 : Radikand, >=0, <2^64
18 // < uintL ergebnis : Wurzel, >=0, <2^32
19 uintL isqrt (uintL x1, uintL x0)
20 {
21   // Methode:
22   // x=0 -> y=0, fertig.
23   // y := 2^k als Anfangswert, wobei k>0, k<=32 mit 2^(2k-2) <= x < 2^(2k) sei.
24   // y := floor((y + floor(x/y))/2) als nächster Wert,
25   // solange z := floor(x/y) < y, setze y := floor((y+z)/2).
26   // y ist fertig.
27   // (Beweis:
28   //  1. Die Folge der y ist streng monoton fallend.
29   //  2. Stets gilt y >= floor(sqrt(x)) (denn für alle y>0 ist
30   //     y + x/y >= 2*sqrt(x) und daher  floor((y + floor(x/y))/2) =
31   //     floor(y/2 + x/(2*y)) >= floor(sqrt(x)) ).
32   //  3. Am Schluß gilt x >= y^2.
33   // )
34      if (x1==0) { return isqrt(x0); } // x klein?
35      { var uintC k2; integerlength32(x1,k2=); // 2^(k2+32-1) <= x < 2^(k2+32)
36       {var uintC k = ceiling(k2+32,2); // k wie oben
37        if (k < 32)
38          // k < 32
39          { var uintL y = ((x1 << (32-k)) | (x0 >> k) | bit(k)) >> 1; // stets 2^(k-1) <= y < 2^k
40            loop
41              { var uintL z;
42                divu_6432_3232(x1,x0,y, z=,); // Dividiere x/y (geht, da x/y < 2^(2k)/2^(k-1) = 2^(k+1) <= 2^32)
43                if (z >= y) break;
44                y = floor(z+y,2); // geht, da z+y < 2*y < 2^(k+1) <= 2^32
45              }
46            return y;
47          }
48          else
49          // k = 32, Vorsicht!
50          { var uintL y = (x1 >> 1) | bit(32-1); // stets 2^(k-1) <= y < 2^k
51            loop
52              { var uintL z;
53                if (x1 >= y) break; // Division x/y ergäbe Überlauf -> z > y
54                divu_6432_3232(x1,x0,y, z=,); // Dividiere x/y
55                if (z >= y) break;
56                y = floor(z+y,2) | bit(32-1); // y muß >= 2^(k-1) bleiben
57              }
58            return y;
59          }
60      }}
61 }
62
63 }  // namespace cln