Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GMP stuck generating same random integers

Tags:

c++

gmp

I would like to generate a random integer z of n bytes such that

2^(n-1) <= z <= 2^n - 1

Whenever I run the following code gmp spits out the same exact integer, what am I doing wrong?

// Random int of n bits.
const auto n_bits = 1024;
mpz_t mpz_int;
gmp_randstate_t state;
mpz_init(mpz_int);
gmp_randinit_default(state);
mpz_rrandomb(mpz_int, state, n_bits);

std::cout<<"Random int generated:"<<std::endl;
std::cout<<mpz_get_str(nullptr, 10, mpz_int)<<std::endl;

The output of mpz_rrandomb changes only when I change the n_bits parameter. I tried this on Ubuntu and MacOS.. I also tried mpz_urandomb -- same problem. I assume I am missing some initializations, I've been going over gmp documentation for hours and I can't find a reason why the above wouldn't work.

To reproduce, stuff the above code into the main function, compile with flags:

g++ main.cpp -O2 -Wall -std=c++14 -lstdc++ -lgmp -lgmpxx

Thank You.

like image 400
lead-free Avatar asked Oct 24 '25 00:10

lead-free


1 Answers

gmp_randinit_default apparently sets the seed to some fixed value. You are supposed to call gmp_randseed or gmp_randseed_ui afterwards to set the seed to your own value which will not be the same on every run.

For an initial test, you could try gmp_randseed_ui(state, getpid()). On Linux you can get a much more random seed by calling getrandom() or reading /dev/urandom. Not sure which of these are provided on MacOS.

like image 144
Nate Eldredge Avatar answered Oct 25 '25 15:10

Nate Eldredge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!