3 * Compute integer square roots
5 * (c) 2000 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of Catacomb.
12 * Catacomb is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU Library General Public License as
14 * published by the Free Software Foundation; either version 2 of the
15 * License, or (at your option) any later version.
17 * Catacomb is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU Library General Public License for more details.
22 * You should have received a copy of the GNU Library General Public
23 * License along with Catacomb; if not, write to the Free
24 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
28 /*----- Header files ------------------------------------------------------*/
32 /*----- Main code ---------------------------------------------------------*/
34 /* --- @mp_sqrt@ --- *
36 * Arguments: @mp *d@ = pointer to destination integer
37 * @mp *a@ = (nonnegative) integer to take square root of
39 * Returns: The largest integer %$x$% such that %$x^2 \le a$%.
41 * Use: Computes integer square roots.
43 * The current implementation isn't very good: it uses the
44 * Newton-Raphson method to find an approximation to %$a$%. If
45 * there's any demand for a better version, I'll write one.
48 mp *mp_sqrt(mp *d, mp *a)
51 mp *q = MP_NEW, *r = MP_NEW;
53 /* --- Sanity preservation --- */
57 /* --- Deal with trivial cases --- */
65 /* --- Find an initial guess of about the right size --- */
72 /* --- Main approximation --- *
74 * We use the Newton-Raphson recurrence relation
76 * %$x_{i+1} = x_i - \frac{x_i^2 - a}{2 x_i}$%
78 * We inspect the term %$q = x^2 - a$% to see when to stop. Increasing
79 * %$x$% is pointless when %$-q < 2 x + 1$%.
96 d = mp_sub(d, d, MP_ONE);
101 /* --- Finished, at last --- */
109 /*----- Test rig ----------------------------------------------------------*/
113 #include <mLib/testrig.h>
115 static int verify(dstr *v)
117 mp *a = *(mp **)v[0].buf;
118 mp *qq = *(mp **)v[1].buf;
119 mp *q = mp_sqrt(MP_NEW, a);
124 fputs("\n*** sqrt failed", stderr);
125 fputs("\n*** a = ", stderr); mp_writefile(a, stderr, 10);
126 fputs("\n*** result = ", stderr); mp_writefile(q, stderr, 10);
127 fputs("\n*** expect = ", stderr); mp_writefile(qq, stderr, 10);
134 assert(mparena_count(MPARENA_GLOBAL) == 0);
139 static test_chunk tests[] = {
140 { "sqrt", verify, { &type_mp, &type_mp, 0 } },
144 int main(int argc, char *argv[])
147 test_run(argc, argv, tests, SRCDIR "/t/mp");
153 /*----- That's all, folks -------------------------------------------------*/