libmp: mpnrand(), what was i *THINKING*
the prior implementation was unneccesarily complicated for no good reason due to me misunderstanding how libc's nrand() works. in contrast to libc, we already generate the *closest* power-of-2 random number with mprand() in the sampling loop.
This commit is contained in:
parent
b80684a1d2
commit
33862ff793
1 changed files with 3 additions and 15 deletions
|
@ -6,30 +6,18 @@
|
||||||
mpint*
|
mpint*
|
||||||
mpnrand(mpint *n, void (*gen)(uchar*, int), mpint *b)
|
mpnrand(mpint *n, void (*gen)(uchar*, int), mpint *b)
|
||||||
{
|
{
|
||||||
mpint *m;
|
|
||||||
int bits;
|
int bits;
|
||||||
|
|
||||||
/* m = 2^bits - 1 */
|
|
||||||
bits = mpsignif(n);
|
bits = mpsignif(n);
|
||||||
m = mpnew(bits+1);
|
if(bits == 0)
|
||||||
mpleft(mpone, bits, m);
|
abort();
|
||||||
mpsub(m, mpone, m);
|
|
||||||
|
|
||||||
if(b == nil){
|
if(b == nil){
|
||||||
b = mpnew(bits);
|
b = mpnew(bits);
|
||||||
setmalloctag(b, getcallerpc(&n));
|
setmalloctag(b, getcallerpc(&n));
|
||||||
}
|
}
|
||||||
|
|
||||||
/* m = m - (m % n) */
|
|
||||||
mpmod(m, n, b);
|
|
||||||
mpsub(m, b, m);
|
|
||||||
|
|
||||||
do {
|
do {
|
||||||
mprand(bits, gen, b);
|
mprand(bits, gen, b);
|
||||||
} while(mpcmp(b, m) >= 0);
|
} while(mpmagcmp(b, n) >= 0);
|
||||||
|
|
||||||
mpmod(b, n, b);
|
|
||||||
mpfree(m);
|
|
||||||
|
|
||||||
return b;
|
return b;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue