将 boost cpp_int 用于 pow() 和 rand() 等函数

Bob*_*Bob 3 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;
Run Code Online (Sandbox Code Playgroud)

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?

Man*_*rse 5

您需要使用pow 的多精度版本(在该页面上搜索pow),然后使用支持通用操作的随机数生成器,例如Boost.Random(或很大程度上基于 Boost 的C++11 标准随机库)。随机的):

#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";
    }
}
Run Code Online (Sandbox Code Playgroud)

实时代码