如何在C ++中处理最大为2 ^ 9000000的整数

Usa*_*hir 3 c++ integer-overflow unsigned-long-long-int

我知道的最大正整数数据类型是unsigned long long。有没有办法在C ++中处理2 ^ 9000000的整数。我在代码块中使用了gcc编译器,但也可以在Visual Studio上工作。

Xir*_*ema 7

您需要某种BigInt库。我个人更喜欢boost.multiprecision,因为它包含了普通代码编写人员所需的大多数实用程序。

在实际使用方面,有两种明显的类型需要考虑。

  • 如果您只需要任意大小的整数,boost::multiprecision::cpp_int则可以通过分配大约900万位数据(略大于1兆字节)并在其中存储整个数字来存储2 ^ 9000000的数字。
  • 如果您需要大数,但又不需要保留最后一位数字的精度,则您会喜欢使用cpp_bin_float后端等方法,尽管为此您可能必须定义自己的模板,因为预烘焙的版本可能不是。还不够大

对于后者,一个潜在的例子是:

using namespace boost::multiprecision;
using my_big_float = number<backends::cpp_bin_float<100, backends::digit_base_2, void, boost::int32_t, -9000000, 9000000>, et_off>;
//Defines the number to have 100 bits of precision, an exponent range from negative
//nine million to positive nine million, and uses 32-bit ints for the internal representation
//of the exponent. Allocator is void (because we don't need it) and et_off just turns off 
//expression templates, which we don't need

int main() {
    my_big_float fl = 5;
    fl = pow(fl, my_big_float{900007});
    std::cout << fl << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

7.88302e+629077
Run Code Online (Sandbox Code Playgroud)

我不知道您的用例是什么,但是我猜想后者对于您的用例会比前者更好。您必须自己决定情况如何。