X-Git-Url: https://git.distorted.org.uk/u/mdw/catacomb/blobdiff_plain/4b536f423c90ba7ca41d3f95f31b17729152a403..6a7dce9165a4a707382e49877334353618fcad9a:/mp-sqrt.c diff --git a/mp-sqrt.c b/mp-sqrt.c index 6b0f602..1491021 100644 --- a/mp-sqrt.c +++ b/mp-sqrt.c @@ -1,13 +1,13 @@ /* -*-c-*- * - * $Id: mp-sqrt.c,v 1.2 2000/10/08 12:02:21 mdw Exp $ + * $Id$ * * Compute integer square roots * * (c) 2000 Straylight/Edgeware */ -/*----- Licensing notice --------------------------------------------------* +/*----- Licensing notice --------------------------------------------------* * * This file is part of Catacomb. * @@ -15,29 +15,18 @@ * it under the terms of the GNU Library General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. - * + * * Catacomb is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. - * + * * You should have received a copy of the GNU Library General Public * License along with Catacomb; if not, write to the Free * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. */ -/*----- Revision history --------------------------------------------------* - * - * $Log: mp-sqrt.c,v $ - * Revision 1.2 2000/10/08 12:02:21 mdw - * Use @MP_EQ@ instead of @MP_CMP@. - * - * Revision 1.1 2000/06/22 19:01:44 mdw - * Compute (approximations to) integer square roots. - * - */ - /*----- Header files ------------------------------------------------------*/ #include "mp.h" @@ -65,14 +54,13 @@ mp *mp_sqrt(mp *d, mp *a) /* --- Sanity preservation --- */ - assert(((void)"imaginary root in mp_sqrt", !(a->f & MP_NEG))); + assert(!MP_NEGP(a)); /* --- Deal with trivial cases --- */ MP_SHRINK(a); - if (a->v == a->vl) { - if (d) - mp_drop(d); + if (MP_ZEROP(a)) { + mp_drop(d); return (MP_ZERO); } @@ -82,7 +70,6 @@ mp *mp_sqrt(mp *d, mp *a) z >>= 1; mp_copy(a); d = mp_lsr(d, a, z); - mp_drop(a); /* --- Main approximation --- * * @@ -97,12 +84,12 @@ mp *mp_sqrt(mp *d, mp *a) for (;;) { q = mp_sqr(q, d); q = mp_sub(q, q, a); - if (q->v == q->vl) + if (MP_ZEROP(q)) break; - if (q->f & MP_NEG) { + if (MP_NEGP(q)) { r = mp_lsl(r, d, 1); r->f |= MP_NEG; - if (MP_CMP(q, <=, r)) + if (MP_CMP(q, >=, r)) break; } mp_div(&r, &q, q, d); @@ -115,9 +102,9 @@ mp *mp_sqrt(mp *d, mp *a) /* --- Finished, at last --- */ + mp_drop(a); mp_drop(q); - if (r) - mp_drop(r); + mp_drop(r); return (d); } @@ -137,7 +124,7 @@ static int verify(dstr *v) if (!MP_EQ(q, qq)) { ok = 0; fputs("\n*** sqrt failed", stderr); - fputs("\n*** a = ", stderr); mp_writefile(a, stderr, 10); + fputs("\n*** a = ", stderr); mp_writefile(a, stderr, 10); fputs("\n*** result = ", stderr); mp_writefile(q, stderr, 10); fputs("\n*** expect = ", stderr); mp_writefile(qq, stderr, 10); fputc('\n', stderr);