diff --git a/include/Void/Math/Numeric.hpp b/include/Void/Math/Numeric.hpp index 0c67480..bb03e60 100644 --- a/include/Void/Math/Numeric.hpp +++ b/include/Void/Math/Numeric.hpp @@ -298,6 +298,47 @@ template return a / b; } +/// Euclidean quotient and remainder for a strictly positive divisor: +/// `a == quotient * divisor + remainder` and `0 <= remainder < divisor`. +template struct EuclideanDivision { + T quotient{}; + T remainder{}; + + [[nodiscard]] constexpr bool + operator==(const EuclideanDivision&) const noexcept = default; +}; + +/// Checked Euclidean division. Unlike C++ integer division (which truncates +/// toward zero), this floors toward negative infinity so the remainder is +/// always nonnegative, e.g. (-1, 32) -> (-1, 31). +/// +/// `divisor == 0` reports `DivisionByZero`; a negative divisor reports +/// `InvalidInput`. The signed minimum is handled without negating it, so no +/// intermediate overflows. +template +[[nodiscard]] constexpr std::expected, Error> + checked_euclidean_div(T a, T divisor) noexcept +{ + if (divisor == T{0}) { + return std::unexpected{Error::DivisionByZero}; + } + if constexpr (std::is_signed_v) { + if (divisor < T{0}) { + return std::unexpected{Error::InvalidInput}; + } + } + T quotient = static_cast(a / divisor); + T remainder = static_cast(a % divisor); + if constexpr (std::is_signed_v) { + if (remainder < T{0}) { + // Truncated division rounded toward zero: step one page down. + quotient = static_cast(quotient - T{1}); + remainder = static_cast(remainder + divisor); + } + } + return EuclideanDivision{.quotient = quotient, .remainder = remainder}; +} + template [[nodiscard]] constexpr std::expected checked_neg(T a) noexcept