Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using boost cpp_int for functions like pow() and rand()

Tags:

c++

boost

pow

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?

like image 684
Bob Avatar asked Sep 05 '25 16:09

Bob


1 Answers

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

like image 147
Mankarse Avatar answered Sep 07 '25 07:09

Mankarse