如何用 C++ 计算 2 ** 128?

how to calculate 2 ** 128 with c++?

我正在尝试用 C++ 计算 2 ** 128,但它溢出了,我得到的值为 0。 关于如何计算这个的任何想法?我还需要在终端上获取它,但 iostream 和 stdio.h 不支持我试过的名为 __int128.

#include <cstring>

int main(){
      unsigned __int128 a = 2;
      for(int i; i < 129; i++){
            a = a * 2;
      }
      std::cout <<  a << std::endl;
}

#include <iostream>
#include <cstring>

int main(){
      long long unsigned int a = 2;
      for(int i; i < 129; i++){
            a = a * 2;
      }
      std::cout <<  a << std::endl;
}

是我试过的代码。

你没有给 i 赋值。

程序的输出会很大,所以你需要做的是; 您可以直接在 std::cout 上设置精度并使用 std::fixed 格式说明符。

int main() {
    
    double a = 2;
      for(int i=0; i < 129; i++){
            a = a * 2;
      }
      cout.precision(200);
      std::cout <<  a << std::endl;
    return 0;
}

为了计算大数,推荐使用Boost multiprecision

#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
using boost::multiprecision::pow;

int main() {
    cpp_int num = boost::multiprecision::pow(cpp_int(2),100);
    std::cout << "This is a big number: " << num <<std::endl;
}

它将打印:

This is a big number: 1267650600228229401496703205376