考虑以下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%安全。
查找示例here。
最佳答案
您将需要一个函数来自动生成所需的号码。
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
函数中具有功能(我找不到一个),请改用该功能。