/* -*-c-*-
*
- * $Id: pgen.c,v 1.7 2001/02/03 16:05:32 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.)
+ *
* 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.
rabin_create(r, ev->m);
rc = PGEN_TRY;
break;
- case PGEN_TRY: {
- mp *a = mprand_range(MP_NEW, ev->m, ev->r, 0);
- rc = rabin_test(r, a);
- mp_drop(a);
- } break;
+ case PGEN_TRY:
+ if (!ev->tests)
+ rc = rabin_rtest(r, MP_TWO);
+ else {
+ mp *a = mprand_range(MP_NEW, ev->m, ev->r, 0);
+ rc = rabin_rtest(r, a);
+ mp_drop(a);
+ }
+ break;
case PGEN_DONE:
rabin_destroy(r);
rc = PGEN_DONE;
ev.m = MP_COPY(m);
else
ev.m = 0;
- ev.steps = steps;
- ev.tests = tests;
+ ev.steps = 0;
+ ev.tests = 0;
ev.r = fibrand_create(0);
/* --- Tell the event handler we're under way --- */
/* --- If decrementing counters is requested, do that --- */
if ((act & A_STEP) && steps) {
- ev.steps--;
- if (!ev.steps) {
+ ev.steps++;
+ if (ev.steps == steps) {
act |= A_EVENT | A_ENDSTEP | A_DONE;
rc = PGEN_ABORT;
}
- ev.tests = tests;
+ ev.tests = 0;
}
if ((act & A_TEST) && tests) {
- ev.tests--;
- if (!ev.tests) {
+ ev.tests++;
+ if (ev.tests == tests) {
act |= A_ENDTEST | A_ENDSTEP | A_DONE;
rc = PGEN_DONE;
}
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