/*
* Miller-Rabin probabilistic primality testing
* Knuth (1981) Seminumerical Algorithms, p.379
* Menezes et al () Handbook, p.39
* 0 if composite; 1 if almost surely prime, Pr(err)<1/4**nrep
*/
int
probably_prime(mpint *n, int nrep)
{
int j, k, rep, nbits, isprime;
mpint *nm1, *q, *x, *y, *r;
if(n->sign < 0)
sysfatal("negative prime candidate");
if(nrep <= 0)
nrep = 18;
k = mptoi(n);
if(k < 2) /* 1 is not prime */
return 0;
if(k == 2 || k == 3) /* 2, 3 is prime */
return 1;
if((n->p[0] & 1) == 0) /* even is not prime */
return 0;
/* test against small prime numbers */
if(smallprimetest(n) < 0)
return 0;
/* fermat test, 2^n mod n == 2 if p is prime */
x = uitomp(2, nil);
y = mpnew(0);
mpexp(x, n, n, y);
k = mptoi(y);
if(k != 2){
mpfree(x);
mpfree(y);
return 0;
}