代码之家  ›  专栏  ›  技术社区  ›  The Quantum Physicist

多重精度:乘以或除以10的巨大幂最便宜的方法是什么?像是10次方的bitshift运算?

  •  0
  • The Quantum Physicist  · 技术社区  · 6 年前

    #include <iostream>
    #include <boost/multiprecision/cpp_int.hpp>
    
    int main()
    {
        boost::multiprecision::cpp_int x = 10;
        x *= 10000000000000000000000000000000000000000000000000000000000000;
        std::cout<<x<<std::endl;
        return 0;
    }
    

    int . 假设我不想涉及字符串,我怎么才能正确地做到这一点呢?有没有像“数字移位运算符”或幂函数这样的东西可以廉价(或尽可能便宜地)做到这一点?

    为什么?因为我写了一个固定精度的库,并且缩放内部整数要求这样的操作是100%安全的。

    找到例子 here

    1 回复  |  直到 6 年前
        1
  •  1
  •   Xirema    6 年前

    你需要一个自动生成数字的函数。

    boost::multiprecision::cpp_int pow(boost::multiprecision::cpp_int value, boost::multiprecision::cpp_int exponent) {
        if(exponent <= 0)
            return 1;
        else if(exponent == 1)
            return value;
        else {
            if(exponent % 2 == 0) {
                return pow(value * value, exponent / 2);
            } else {
                return value * pow(value, exponent - 1);
            }
        }
    }
    
    int main()
    {
        boost::multiprecision::cpp_int x = 10;
        x *= pow(10, 61);//I believe this is the correct number of 0's from manually counting
        std::cout<<x<<std::endl;
        return 0;
    }
    

    如果增强多精度有一个烤箱 pow 函数(我找不到),用它代替。