如果你只需要做加法
#include<cstdint>
#include<limits>
#include<utility>
using std::uint64_t;
std::pair<uint64_t, int> add_with_carry(uint64_t a, uint64_t b)
{
if(a > std::numeric_limits<uint64_t>::max() - b)
return {a + b, 1};
else
return {a + b, 0};
}
auto [sum, carry] = add_with_carry(a, b);
并扩展至任意链接添加
std::pair<uint64_t, int> add_with_carry(std::pair<uint64_t, int> a)
{
return a;
}
template<typename... Addends>
std::pair<uint64_t, int> add_with_carry(std::pair<uint64_t, int> a, uint64_t b, Addends... addends)
{
if(b > std::numeric_limits<uint64_t>::max() - a.first)
return add_with_carry(std::pair<uint64_t, int>{b + a.first, 1 + a.second}, addends...);
else
return add_with_carry(std::pair<uint64_t, int>{b + a.first, a.second}, addends...);
}
template<typename... Addends>
std::pair<uint64_t, int> add_with_carry(uint64_t a, Addends... addends)
{
return add_with_carry(std::pair<uint64_t, int>{a, 0}, addends...);
}
auto [sum, carry] = add_with_carry(a, b, c, d, e);
有可能与倍表达式来实现这个更优雅的方式。
警告:,如果你有一个呼叫2个十亿变量add_with_carry
你可能溢出进int
。祝你好运,虽然...
如果你想保持便携和精益,你不能摆脱使用BigInt,无论是自己的或外部的图书馆。否则一些装配不会伤害你。 x86_64也有一个128位整数。 – DeiDei
您可以将64位值分为低32位值和高32位值,而不是总和低位32位值为64位并得到总和和溢出,而不是相似总和高部分和低部分溢出,因此您将拥有较低的32位的结果,更高的32位结果和溢出 –