未签名的长期添加和多个操作数
unsigned long long addition with multiple operands
unsigned long long a = 18446744073709551615
unsigned long long b = 18446744073709551614
unsigned long long c = 18446744073709551613
unsigned long long d = 18446744073709551612
unsigned long long e = 18446744073709551611
我想添加a b c d e并获得结果(64位(和 crand ,因为它将超过64位。我应该使用BigInteger库吗?有什么更简单的方法可以做这种事情吗?我发现使用BigInteger的大多数东西都很复杂,尽管我的问题似乎很简单,但我找不到非常相似的例子。
如果您只需要添加
#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);
可能有一种更优雅的方式可以用折叠表达式实现此功能。
警告:如果在呼叫add_with_carry
中有20亿个变量,则可能会溢出int
。好运,但是...
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 控制允许动态运行c++的并发操作数
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 只能向C++添加一定数量的字符
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 需要左键作为赋值的左操作数?? 在链表中添加Add_End、删除和Delete_Front?
- 未签名的长期添加和多个操作数
- 添加数组元素:需要左键作为赋值的左操作数
- 如何在LLVM中为MDNode或元数据添加多个操作数