Need to store very large integers, so I'm using boost::multiprecision::cpp_int. Problem is, I can't figure out how to use this to get the values I want from other functions like pow() and rand() when using this new type.
I need to store a very large number that is calculated by exponentiation. But the pow() function itself cannot handle such large numbers and rand() returns basic integers.
More specifically, I simply need to store the value 2^1024 and generate a random number between 1 and 2^1024. But I've been really struggling to get this to work.
cpp_int x = pow(2,1024);
x = rand() % x + 1;
Stuff like this doesn't work for the reasons I stated above. I've also tried boost::multiprecision::pow, but that doesn't seem to work with cpp_int. What hoops do I need to jump through to make these relatively simple operations work with large integers?
You need to use the 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 that was heavily based on Boost.Random):
#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";
}
}
Live code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With