6 * Miller-Rabin probabilistic primality testing
7 * Knuth (1981) Seminumerical Algorithms, p.379
8 * Menezes et al () Handbook, p.39
9 * 0 if composite; 1 if almost surely prime, Pr(err)<1/4**nrep
12 probably_prime(mpint *n, int nrep)
14 int j, k, rep, nbits, isprime;
15 mpint *nm1, *q, *x, *y, *r;
18 sysfatal("negative prime candidate");
24 if(k < 2) /* 1 is not prime */
26 if(k == 2 || k == 3) /* 2, 3 is prime */
28 if((n->p[0] & 1) == 0) /* even is not prime */
31 /* test against small prime numbers */
32 if(smallprimetest(n) < 0)
35 /* fermat test, 2^n mod n == 2 if p is prime */
48 mpsub(n, mpone, nm1); /* nm1 = n - 1 */
51 mpright(nm1, k, q); /* q = (n-1)/2**k */
53 for(rep = 0; rep < nrep; rep++){
55 /* find x = random in [2, n-2] */
56 r = mprand(nbits, prng, nil);
59 if(mpcmp(x, mpone) > 0)
66 if(mpcmp(y, mpone) == 0 || mpcmp(y, nm1) == 0)
75 mpmod(x, n, y); /* y = y*y mod n */
76 if(mpcmp(y, nm1) == 0)
78 if(mpcmp(y, mpone) == 0){