简体   繁体   English

GMP 卡在生成相同的随机整数

[英]GMP stuck generating same random integers

I would like to generate a random integer z of n bytes such that我想生成一个 n 字节的随机 integer z 使得

2^(n-1) <= z <= 2^n - 1 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?每当我运行以下代码 gmp 吐出完全相同的 integer 时,我做错了什么?

// 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. mpz_rrandom 的mpz_rrandomb仅在我更改n_bits参数时才会更改。 I tried this on Ubuntu and MacOS.. I also tried mpz_urandomb -- same problem.我在 Ubuntu 和 MacOS 上试过这个。我也试过mpz_urandomb同样的问题。 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.我假设我错过了一些初始化,我已经阅读了几个小时的 gmp 文档,但我找不到上述方法不起作用的原因。

To reproduce, stuff the above code into the main function, compile with flags:要重现,将上述代码填充到主 function 中,使用标志编译:

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

Thank You.谢谢你。

gmp_randinit_default apparently sets the seed to some fixed value. gmp_randinit_default显然将种子设置为某个固定值。 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.您应该在之后调用gmp_randseedgmp_randseed_ui将种子设置为您自己的值,这在每次运行时都不相同。

For an initial test, you could try gmp_randseed_ui(state, getpid()) .对于初始测试,您可以尝试gmp_randseed_ui(state, getpid()) On Linux you can get a much more random seed by calling getrandom() or reading /dev/urandom .在 Linux 上,您可以通过调用getrandom()或读取/dev/urandom获得更多随机种子。 Not sure which of these are provided on MacOS.不确定 MacOS 上提供了哪些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM