<numeric>
Saturating Arithmetic
Saturating arithmetic avoids the possibility of overflow or underflow, by clamping the value to a defined range should either of these situations occur. This means that on overflow the result will be the maximum value of the type, and on underflow it will be the minimum value of the type. The following functions are provided for saturating arithmetic, and they do not require C++26.
#include <boost/int128/numeric.hpp>
namespace boost {
namespace int128 {
constexpr uint128_t add_sat(const uint128_t& lhs, const uint128_t& rhs) noexcept;
constexpr int128_t add_sat(const int128_t& lhs, const int128_t& rhs) noexcept;
constexpr uint128_t sub_sat(const uint128_t& lhs, const uint128_t& rhs) noexcept;
constexpr int128_t sub_sat(const int128_t& lhs, const int128_t& rhs) noexcept;
constexpr uint128_t mul_sat(const uint128_t& lhs, const uint128_t& rhs) noexcept;
constexpr int128_t mul_sat(const int128_t& lhs, const int128_t& rhs) noexcept;
constexpr uint128_t div_sat(const uint128_t& lhs, const uint128_t& rhs) noexcept;
constexpr int128_t div_sat(const int128_t& lhs, const int128_t& rhs) noexcept;
} // namespace int128
} // namespace boost
Saturating Cast
This function allows a LibraryIntegerType (i.e. uint128_t or int128_t) to be safely casted to another integer type to include built-in and hardware integer types (TargetIntegerType).
Should the TargetIntegerType not be able to represent the value of the LibraryIntegerType, it will be clamped to either the maximum or minimum value of TargetIntegerType depending on whether the situation is overflow or underflow.
namespace boost {
namespace int128 {
template <typename TargetIntegerType, typename LibraryIntegerType>
constexpr TargetIntegerType saturate_cast(const LibraryIntegerType& x) noexcept;
} // namespace int128
} // namespace boost
Greatest Common Divisor (GCD)
Computes the greatest common divisor of a and b.
namespace boost {
namespace int128 {
constexpr uint128_t gcd(const uint128_t& a, const uint128_t& b) noexcept;
constexpr int128_t gcd(const int128_t& a, const int128_t& b) noexcept;
} // namespace int128
} // namespace boost
Least Common Multiple (LCM)
Computes the least common multiple of a and b.
namespace boost {
namespace int128 {
constexpr uint128_t lcm(const uint128_t& a, const uint128_t& b) noexcept;
constexpr int128_t lcm(const int128_t& a, const int128_t& b) noexcept;
} // namespace int128
} // namespace boost