sad*_*ave 0 c++ random biginteger gmp
我正在尝试使用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
Run Code Online (Sandbox Code Playgroud)
我知道这不是很多,但是,我不知道在这一点上语法甚至是什么,我已经尝试了几件事,但我发现没有什么能让我告诉GMP使用高和数字生成的低范围.
思考?
功能:void mpz_urandomb (mpz_t rop, gmp_randstate_t state, mp_bitcnt_t n)
在 0 到 2^n?1 范围内生成一个均匀分布的随机整数,包括
因此,取 210 - 199,并将其用作 n,生成一个随机数并将结果添加到 pow(2,199)。
如果你想要比 2 的上限更精细的东西,这对你不起作用。您可以使用上述相同的技术尝试 unsigned int 大小的随机函数:
— 功能:unsigned long gmp_urandomm_ui(gmp_randstate_t 状态,unsigned long n)
返回 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: %Zd\n", 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);
}
Run Code Online (Sandbox Code Playgroud)
谢谢@Less的逻辑和帮助!
| 归档时间: |
|
| 查看次数: |
2842 次 |
| 最近记录: |