Rename MP_IS* to MP_*P, for consistency's sake. Use these macros more often.
[u/mdw/catacomb] / mpreduce.c
index 7d31334..13e705e 100644 (file)
@@ -1,6 +1,6 @@
 /* -*-c-*-
  *
- * $Id: mpreduce.c,v 1.2 2004/04/08 01:36:15 mdw Exp $
+ * $Id$
  *
  * Efficient reduction modulo nice primes
  *
@@ -64,7 +64,7 @@ void mpreduce_create(mpreduce *r, mp *p)
 
   /* --- Fill in the easy stuff --- */
 
-  assert(MP_ISPOS(p));
+  assert(MP_POSP(p));
   d = mp_bits(p);
   r->lim = d/MPW_BITS;
   r->s = d%MPW_BITS;
@@ -253,7 +253,7 @@ mp *mpreduce_do(mpreduce *r, mp *d, mp *x)
 
   /* --- If source is negative, divide --- */
 
-  if (MP_ISNEG(x)) {
+  if (MP_NEGP(x)) {
     mp_div(0, &d, x, r->p);
     return (d);
   }
@@ -335,12 +335,18 @@ mp *mpreduce_exp(mpreduce *mr, mp *d, mp *a, mp *e)
   mp *spare = (e->f & MP_BURN) ? MP_NEWSEC : MP_NEW;
 
   MP_SHRINK(e);
-  if (!MP_LEN(e))
+  MP_COPY(a);
+  if (MP_ZEROP(e))
     ;
-  else if (MP_LEN(e) < EXP_THRESH)
-    EXP_SIMPLE(x, a, e);
-  else
-    EXP_WINDOW(x, a, e);
+  else {
+    if (MP_NEGP(e))
+      a = mp_modinv(a, a, mr->p);
+    if (MP_LEN(e) < EXP_THRESH)
+      EXP_SIMPLE(x, a, e);
+    else
+      EXP_WINDOW(x, a, e);
+  }
+  mp_drop(a);
   mp_drop(d);
   mp_drop(spare);
   return (x);