C++GMP生成随机数
C++ GMP Generating Random Number
我正在尝试使用 GMP 库在C++生成一个巨大的随机数,但在弄清楚语法时遇到问题。这与我发现的其他示例略有不同,因为我需要为随机数设置一个下限和上限。这是我需要做的:
mpz_class high, low;
low = pow(2,199);
high = pow(2,210);
// code to use the high and low numbers to generate the random number
我知道这没什么可说的,但同样,我不确定此时的语法是什么,我已经尝试了几件事,但我发现没有什么能让我告诉 GMP 使用高低范围进行数字生成。
思潮?
来自gmp lib
文档功能:空隙mpz_urandomb(mpz_t rop,gmp_randstate_t状态, mp_bitcnt_t n)
生成 0 到 范围内的均匀分布的随机整数 2^n−1,包括
因此,取 210 - 199,并将其用作 n,生成一个随机数并将结果添加到 pow(2,199)。
如果您想要比 2 次幂上限更精细的东西,这对您不起作用。 您可以使用与上述相同的技术尝试无符号的 int 大小的随机函数:
— 功能:无符号长gmp_urandomm_ui(gmp_randstate_t状态,无符号长 n)
返回 0 到 n-1(包括 0 和 n-1)范围内的均匀分布的随机数。
在这里,您将找到您的粒度范围并将其用于 n。 然后将随机数添加到您的较低值。 限制为 n 必须小于 MAXUINT,通常为 2^32 -1
使用 @Less 提出的逻辑,我编写了以下内容来解决我的问题:
void
makeprime ()
{
// *********************** VARIABLE DECLARATION *********************** //
// initilize the variables as gmp class instances
mpz_t l, rand;
unsigned long seed;
// perform inits to create variable pointers with 0 value
mpz_inits(l, rand);
//mpz_init(rand);
// calculate the random number floor
mpz_ui_pow_ui(l, 2, 199);
// initilze the state object for the random generator functions
gmp_randstate_t rstate;
// initialize state for a Mersenne Twister algorithm. This algorithm is fast and has good randomness properties.
gmp_randinit_mt(rstate);
// create the generator seed for the random engine to reference
gmp_randseed_ui(rstate, seed);
/*
Function:
int mpz_probab_prime_p (const mpz_t n, int reps)
Determine whether n is prime. Return 2 if n is definitely prime, return 1 if n is probably prime (without being certain),
or return 0 if n is definitely composite.
*/
do {
// return a uniformly distributed random number in the range 0 to n-1, inclusive.
mpz_urandomb(rand, rstate, 310);
// add the random number to the low number, which will make sure the random number is between the low and high ranges
mpz_add(rand, rand, l);
gmp_printf("randomly generated number: %Zdn", rand);
} while ( !(mpz_probab_prime_p(rand, 25)) );
// *********************** GARBAGE COLLECTION *********************** //
// empty the memory location for the random generator state
gmp_randclear(rstate);
// clear the memory locations for the variables used to avoid leaks
mpz_clear(l);
mpz_clear(rand);
}
感谢@Less的逻辑和帮助!
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 整数不会重复超过随机数
- if数组上的随机数
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 半随机数生成C++
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 使用 GMP 的 while 循环出现问题
- 有没有办法在 c++ 中同时生成随机数?如果没有,是否有解决方法?
- 具有随机数的二维数组不会更改
- 随机数未达到限制
- 有没有一个 c++ gmp 库函数与 python gmpy2 库 divm(..) 函数相同?
- 我想生成许多矩阵并用随机数填充它
- <random>在实践中应该实际使用哪个随机数引擎? std::mt19937?
- 制作具有平均值的随机数生成器
- 为什么 rand 不在我的代码中生成随机数?
- 使用 MinGW 在 Windows 上安装 GMP 时出错
- Diffie-Hellman密钥交换的C GMP随机数生成
- c++中使用GMP的随机数生成
- 如何使用GMP生成一定范围内的随机数
- C++GMP生成随机数