How to generate different random numbers?

Sisyphus sisyphus1 at optusnet.com.au
Wed Feb 1 10:59:02 CET 2006


----- Original Message ----- 
From: "Forum Joiner"
.
.
>
> Some code examples would be very appreciated.
>
> I know how to generate numbers from 1 to 2^10, but how to get numbers only
> in the 2^9 ... 2^10 interval?
> I don't want to filter the numbers from 1 to 2^10, rather I want to
generate
> directly only numbers from 2^9 ... 2^10 interval.
>

You want numbers in the range 512 ... 1023 (inclusive). That is, you want a
random 10-bit number - except the most significant bit has to be '1' - the
other 9 bits are random, but the msb is not. That's the same as taking a
random number in the range 0 ... 2^9 - 1, and adding 2^9 (ie 512) to it -
which is precisely what the demo (see below my sig) does.

Getting different random numbers each time you run the program is just a
matter of making sure that the seed is different. I've used the system
time - so you'll get different results each time, as long as each instance
of the program is separated by more than a second. If you run multiple
instances of the program within one second of each other you risk having the
same output repeated.

Note that 'system time' is not a good random seed where secrecy is an issue.
Anyone that guesses the type of prng you used and guesses that the prng was
seeded using 'system time' would quickly be able to reproduce the
sequence(s) you have. You might also wish to seed with an mpz_t rather than
an unsigned long - in which case you use gmp_randseed() instead of
gmp_randseed_ui().

Hope this helps.

Cheers,
Rob

#include <stdio.h>
#include <gmp.h>

int main(void) {
    gmp_randstate_t s;
    unsigned long seed, i;
    mpz_t rop[10];

    seed = time(NULL); // system time

    for(i = 0; i < 10; ++i) mpz_init(rop[i]);

    gmp_randinit_default(s);
    gmp_randseed_ui(s, seed);

    for(i = 0; i < 10; ++i) {
       mpz_urandomb(rop[i], s, 9);
       mpz_add_ui(rop[i], rop[i], 512);
       }
    for(i = 0; i < 10; ++i) gmp_printf("%Zd ", rop[i]);
    printf("\n");

    // Clean up
    gmp_randclear(s);
    for(i = 0; i < 10; ++i) mpz_clear(rop[i]);

    return 0;
}



More information about the gmp-discuss mailing list