From 33862ff7936eb8be9380ce1332a3cfd7ed703672 Mon Sep 17 00:00:00 2001 From: cinap_lenrek Date: Mon, 29 Aug 2016 00:45:16 +0200 Subject: [PATCH] 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. --- sys/src/libmp/port/mpnrand.c | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/sys/src/libmp/port/mpnrand.c b/sys/src/libmp/port/mpnrand.c index aa6a1e273..278547ca6 100644 --- a/sys/src/libmp/port/mpnrand.c +++ b/sys/src/libmp/port/mpnrand.c @@ -6,30 +6,18 @@ mpint* mpnrand(mpint *n, void (*gen)(uchar*, int), mpint *b) { - mpint *m; int bits; - /* m = 2^bits - 1 */ bits = mpsignif(n); - m = mpnew(bits+1); - mpleft(mpone, bits, m); - mpsub(m, mpone, m); - + if(bits == 0) + abort(); if(b == nil){ b = mpnew(bits); setmalloctag(b, getcallerpc(&n)); } - - /* m = m - (m % n) */ - mpmod(m, n, b); - mpsub(m, b, m); - do { mprand(bits, gen, b); - } while(mpcmp(b, m) >= 0); - - mpmod(b, n, b); - mpfree(m); + } while(mpmagcmp(b, n) >= 0); return b; }