对 pow() 和 rand() 等函数使用 boost cpp_int
Using boost cpp_int for functions like pow() and rand()
需要存储非常大的整数,所以我使用 boost::multiprecision::cpp_int。问题是,在使用这种新类型时,我不知道如何使用它从 pow() 和 rand() 等其他函数中获取我想要的值。
我需要存储一个非常大的数,该数是通过求幂计算的。但是 pow() 函数本身无法处理如此大的数字和 rand() returns 基本整数。
更具体地说,我只需要存储值 2^1024 并生成一个介于 1 和 2^1024 之间的随机数。但我一直在努力让它发挥作用。
cpp_int x = pow(2,1024);
x = rand() % x + 1;
由于我上面提到的原因,这样的东西不起作用。我也尝试过 boost::multiprecision::pow,但这似乎不适用于 cpp_int。要使这些相对简单的操作适用于大整数,我需要跳过哪些环节?
您需要使用在很大程度上基于 Boost.Random 的 multiprecision version of pow (search for pow
on that page), and then use a random number generator that supports generic operations, such as Boost.Random (or the C++11 standard random library:
#include <iostream>
#include <boost/random/random_device.hpp>
#include <boost/random.hpp>
#include <boost/multiprecision/cpp_int.hpp>
int main()
{
namespace mp = boost::multiprecision;
mp::cpp_int x = mp::pow(mp::cpp_int(2), 1024);
std::cout << x << "\n";
boost::random::random_device gen;
boost::random::uniform_int_distribution<mp::cpp_int> ui(1, x);
for(unsigned i = 0; i < 10; ++i) {
mp::cpp_int y = ui(gen);
std::cout << y << "\n";
}
}
需要存储非常大的整数,所以我使用 boost::multiprecision::cpp_int。问题是,在使用这种新类型时,我不知道如何使用它从 pow() 和 rand() 等其他函数中获取我想要的值。
我需要存储一个非常大的数,该数是通过求幂计算的。但是 pow() 函数本身无法处理如此大的数字和 rand() returns 基本整数。
更具体地说,我只需要存储值 2^1024 并生成一个介于 1 和 2^1024 之间的随机数。但我一直在努力让它发挥作用。
cpp_int x = pow(2,1024);
x = rand() % x + 1;
由于我上面提到的原因,这样的东西不起作用。我也尝试过 boost::multiprecision::pow,但这似乎不适用于 cpp_int。要使这些相对简单的操作适用于大整数,我需要跳过哪些环节?
您需要使用在很大程度上基于 Boost.Random 的 multiprecision version of pow (search for pow
on that page), and then use a random number generator that supports generic operations, such as Boost.Random (or the C++11 standard random library:
#include <iostream>
#include <boost/random/random_device.hpp>
#include <boost/random.hpp>
#include <boost/multiprecision/cpp_int.hpp>
int main()
{
namespace mp = boost::multiprecision;
mp::cpp_int x = mp::pow(mp::cpp_int(2), 1024);
std::cout << x << "\n";
boost::random::random_device gen;
boost::random::uniform_int_distribution<mp::cpp_int> ui(1, x);
for(unsigned i = 0; i < 10; ++i) {
mp::cpp_int y = ui(gen);
std::cout << y << "\n";
}
}