/* -*-c-*-
*
- * $Id: mp-modsqrt.c,v 1.2 2000/10/08 12:02:21 mdw Exp $
+ * $Id: mp-modsqrt.c,v 1.5 2004/04/08 01:36:15 mdw Exp $
*
* Compute square roots modulo a prime
*
* MA 02111-1307, USA.
*/
-/*----- Revision history --------------------------------------------------*
- *
- * $Log: mp-modsqrt.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:31 mdw
- * Compute square roots in a prime field.
- *
- */
-
/*----- Header files ------------------------------------------------------*/
#include "fibrand.h"
* work if %$p$% is composite: you must factor the modulus, take
* a square root mod each factor, and recombine the results
* using the Chinese Remainder Theorem.
+ *
+ * We guarantee that the square root returned is the smallest
+ * one (i.e., the `positive' square root).
*/
mp *mp_modsqrt(mp *d, mp *a, mp *p)
/* --- Cope if %$a \not\in Q_p$% --- */
if (mp_jacobi(a, p) != 1) {
- if (d)
- mp_drop(d);
+ mp_drop(d);
return (0);
}
/* --- Find the inverse of %$a$% --- */
- ainv = MP_NEW;
- mp_gcd(0, &ainv, 0, a, p);
+ ainv = mp_modinv(MP_NEW, a, p);
/* --- Split %$p - 1$% into a power of two and an odd number --- */
/* --- Now to really get going --- */
mpmont_create(&mm, p);
+ b = mpmont_mul(&mm, b, b, mm.r2);
c = mpmont_expr(&mm, b, b, t);
t = mp_add(t, t, MP_ONE);
t = mp_lsr(t, t, 1);
- r = mpmont_expr(&mm, t, a, t);
+ dd = mpmont_mul(&mm, MP_NEW, a, mm.r2);
+ r = mpmont_expr(&mm, t, dd, t);
+ mp_drop(dd);
ainv = mpmont_mul(&mm, ainv, ainv, mm.r2);
mone = mp_sub(MP_NEW, p, mm.r);
c = mpmont_reduce(&mm, c, c);
}
- /* --- Done, so tidy up --- */
+ /* --- Done, so tidy up --- *
+ *
+ * Canonify the answer.
+ */
d = mpmont_reduce(&mm, d, r);
+ r = mp_sub(r, p, d);
+ if (MP_CMP(r, <, d)) { mp *tt = r; r = d; d = tt; }
mp_drop(ainv);
mp_drop(r); mp_drop(c);
- if (dd)
- mp_drop(dd);
+ mp_drop(dd);
mp_drop(mone);
mpmont_destroy(&mm);
ok = 0;
else if (MP_EQ(r, rr))
ok = 1;
- else {
- r = mp_sub(r, p, r);
- if (MP_EQ(r, rr))
- ok = 1;
- }
if (!ok) {
fputs("\n*** fail\n", stderr);
mp_drop(a);
mp_drop(p);
- if (r)
- mp_drop(r);
+ mp_drop(r);
mp_drop(rr);
assert(mparena_count(MPARENA_GLOBAL) == 0);
return (ok);