Add cyclic group abstraction, with test code. Separate off exponentation
[u/mdw/catacomb] / pgen.c
diff --git a/pgen.c b/pgen.c
index dca61d9..9cc4334 100644 (file)
--- a/pgen.c
+++ b/pgen.c
@@ -1,6 +1,6 @@
 /* -*-c-*-
  *
- * $Id: pgen.c,v 1.8 2002/01/13 13:42:53 mdw Exp $
+ * $Id: pgen.c,v 1.9 2004/04/01 12:50:09 mdw Exp $
  *
  * Prime generation glue
  *
 /*----- Revision history --------------------------------------------------* 
  *
  * $Log: pgen.c,v $
+ * Revision 1.9  2004/04/01 12:50:09  mdw
+ * Add cyclic group abstraction, with test code.  Separate off exponentation
+ * functions for better static linking.  Fix a buttload of bugs on the way.
+ * Generally ensure that negative exponents do inversion correctly.  Add
+ * table of standard prime-field subgroups.  (Binary field subgroups are
+ * currently unimplemented but easy to add if anyone ever finds a good one.)
+ *
  * Revision 1.8  2002/01/13 13:42:53  mdw
  * More efficient Rabin-Miller test: with random witnesses, skip redundant
  * Montgomerization.  (Being bijective, it can't affect the distribution.)
@@ -334,6 +341,37 @@ mp *pgen(const char *name, mp *d, mp *m, pgen_proc *event, void *ectx,
   return (ev.m);
 }
 
+/* --- @pgen_primep@ --- *
+ *
+ * Arguments:  @mp *p@ = a number to check
+ *             @grand *gr@ = a random number source
+ *
+ * Returns:    Nonzero if @p@ is really prime.
+ */
+
+int pgen_primep(mp *p, grand *gr)
+{
+  int i = rabin_iters(mp_bits(p));
+  rabin r;
+  mp *x = MP_NEW;
+
+  if (MP_ISNEG(p)) return (0);
+  switch (pfilt_smallfactor(p)) {
+    case PGEN_DONE: return (1);
+    case PGEN_FAIL: return (0);
+  }
+  rabin_create(&r, p);
+  while (i) {
+    x = mprand_range(x, p, gr, 0);
+    if (rabin_rtest(&r, x) == PGEN_FAIL)
+      break;
+    i--;
+  }
+  MP_DROP(x);
+  rabin_destroy(&r);
+  return (!i);
+}
+
 /*----- Test rig ----------------------------------------------------------*/
 
 #ifdef TEST_RIG