C++GMP生成随机数

C++ GMP Generating Random Number

本文关键字:随机数 C++GMP      更新时间:2023-10-16

我正在尝试使用 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的逻辑和帮助!