[bigint] Question

Matt McCutchen <matt at mattmccutchen.net>
Sun Jun 20 12:30:28 PDT 2010


On Sun, 2010-06-20 at 15:58 -0300, Nicolás Carrasco wrote:
> I need to write a pseudo random number generator, for first aproach
> using standard c++ rand function.
> 
> Can you give me an example o how to put random generated bits by
> rand() to a BigUnsigned?

There are two general approaches:

1. Cast the return value of rand() to a BigUnsigned and use the bitwise
shift and OR operators to deposit it in the appropriate place, something
like this:

BigUnsigned buf(0);
for (int i = 0; i < n; i++)
    buf |= BigUnsigned(rand()) << (i * RAND_BITS);

This is really easy, but unfortunately it takes quadratic time to fiddle
with all the low-order zeros created by the shifting.

2. Fill an array of some integral type with random bits from rand() and
pass it to the dataToBigInteger function.  (There should really be a
BigUnsigned version of that function.)  Unfortunately, if your rand() is
like mine and provides 31 random bits at a time, you'll need to either
take extra steps to get a 32nd bit or take only 16 of the bits and waste
the rest.

Random number generation is something that perhaps the library could
support better.  I'll keep it in mind.

-- 
Matt




More information about the bigint mailing list