【问题标题】:how to calculate 2 ** 128 with c++?如何用 C++ 计算 2 ** 128?
【发布时间】:2021-07-16 11:46:39
【问题描述】:

我正在尝试用 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;
}

是我尝试过的代码。

【问题讨论】:

  • nitpick:我记得有些语言使用a ** b 来表示 a 的 b 次方,但我不知道这是常见的表示法。常见的是a ^ b,不幸的是这也令人困惑,因为^ 是一个逻辑运算符。
  • 您可以使用类似:boost.orgsourceforge.net/projects/cpp-bigint 来执行此类计算。看stackoverflow.com/questions/1188939/…
  • 还有一个库提供uint128_t` or `uint256_t
  • 2 ** 128 相当于将 1 左移 128 次。无需乘以任何东西或使用任何长的数学库。
  • 如果是琐碎的工作,不必用 c++ 来完成,那么你可以尝试一下 python 一行:2 ** 128

标签: c++ integer numbers


【解决方案1】:

你没有给 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;
}

【讨论】:

  • a ^ b 也令人困惑,尤其是对于 C++ 开发人员而言。 a ** b 不太常见,但很明确。
  • ^ 用于 (La)TeX、Matlab 或 Mathematica。但不是在 C/C++ 中,它确实意味着按位异或。
  • @DanielLangr ^ 用于TeX(在数学模式下)用于上标。它只是间接的(因为书面数学通常表示使用上标的“权力”)。然而,在数学符号中,上标可以(并且实际上是)用来表示作者想要的任何东西 - 只要它们说明了含义。
【解决方案2】:

为了计算大数,建议使用Boost multiprecision library

#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

【讨论】:

    猜你喜欢
    • 2019-08-29
    • 2011-07-25
    • 2017-10-08
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多