plan9port

fork of plan9port with libvec, libstr and libsdb
Log | Files | Refs | README | LICENSE

genprime.c (544B)


      1 #include "os.h"
      2 #include <mp.h>
      3 #include <libsec.h>
      4 
      5 /*  generate a probable prime.  accuracy is the miller-rabin interations */
      6 void
      7 genprime(mpint *p, int n, int accuracy)
      8 {
      9 	mpdigit x;
     10 
     11 	/* generate n random bits with high and low bits set */
     12 	mpbits(p, n);
     13 	genrandom((uchar*)p->p, (n+7)/8);
     14 	p->top = (n+Dbits-1)/Dbits;
     15 	x = 1;
     16 	x <<= ((n-1)%Dbits);
     17 	p->p[p->top-1] &= (x-1);
     18 	p->p[p->top-1] |= x;
     19 	p->p[0] |= 1;
     20 
     21 	/* keep icrementing till it looks prime */
     22 	for(;;){
     23 		if(probably_prime(p, accuracy))
     24 			break;
     25 		mpadd(p, mptwo, p);
     26 	}
     27 }