如何使用 boost 生成不同位的随机多精度整数?

How can I generate random multiprecision ints of different bits using boost?

我需要生成大量不同位的随机多精度整数 (boost mpx_int)。我当前的方法基于以下两个示例:boost multiprecision random, constexpr array。要以这种方式生成随机数,我需要位数作为 constexpr。我可以生成一个 constexpr 整数数组,但后来我卡住了,因为我无法从 for 循环中访问它们。

代码示例:

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/random.hpp>
#include <iostream>

using namespace std;
using namespace boost::multiprecision;
using namespace boost::random;

template <int bit_limit>
struct N_bit_nums
{
    constexpr N_bit_nums() : bits{}
    {
        for (int i = 0; i < bit_limit; ++i)
        {
            bits[i] = i + 1;
        }
    }

    int bits[bit_limit];
};

int main()
{
    constexpr int bit_limit = 3; // this will actually be on the order of 10^6
    constexpr N_bit_nums<bit_limit> n_bit_nums{};

    for (int i = 0; i < bit_limit; ++i)
    {
        independent_bits_engine<mt19937, n_bit_nums.bits[i], cpp_int> generator; // error: the value of ‘i’ is not usable in a constant expression
        cpp_int rand_num = generator();
        cout << rand_num << "\n"; // just to see what is going on while testing
    }

    return 0;
}

我能够通过将 independent_bits_engine 固定为所需的最大位数然后屏蔽为所需的位数来实现此目的。

示例:

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/random.hpp>
#include <iostream>

using namespace std;
using namespace boost::multiprecision;
using namespace boost::random;

int main()
{
    constexpr int bit_limit = 100;
    independent_bits_engine<mt19937, bit_limit, cpp_int> generator;

    // prints random numbers of bit sizes from 1 to bit_limit
    for (int n = 1; n <= bit_limit; n++)
    {
        cpp_int rand_num = generator();              // next random value
        cpp_int n_bit_mask = pow(cpp_int{2}, n) - 1; // n bits mask
        cpp_int n_bit_num = rand_num & n_bit_mask;   // take n lsb
        cout << n_bit_num << "\n";                   // print the n bit random number
    }

    return 0;
}