Gather up another utility.
[u/mdw/catacomb] / pgen.c
diff --git a/pgen.c b/pgen.c
index dca61d9..ac8db38 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.10 2004/04/08 01:36:15 mdw Exp $
  *
  * Prime generation glue
  *
  * MA 02111-1307, USA.
  */
 
-/*----- Revision history --------------------------------------------------* 
- *
- * $Log: pgen.c,v $
- * 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.)
- *
- * Revision 1.7  2001/02/03 16:05:32  mdw
- * Now @mp_drop@ checks its argument is non-NULL before attempting to free
- * it.  Note that the macro version @MP_DROP@ doesn't do this.
- *
- * Revision 1.6  2000/10/08 12:11:22  mdw
- * Use @MP_EQ@ instead of @MP_CMP@.
- *
- * Revision 1.5  2000/06/17 11:52:36  mdw
- * Signal a pgen abort if the jump and base share a common factor.
- *
- * Revision 1.4  1999/12/22 16:01:11  mdw
- * Same file, completely different code.  Main interface for new prime-
- * search system.
- *
- */
-
 /*----- Header files ------------------------------------------------------*/
 
 #include <assert.h>
@@ -334,6 +311,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