0

考虑以下 MCVE:

#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% 安全的。

在此处查找示例。

4

1 回答 1

1

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

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;
}

如果 boost.multiprecision 有内置pow函数(我找不到),请改用它。

于 2019-01-04T21:32:15.463 回答