Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make addmod/mulmod constexpr #314

Merged
merged 1 commit into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions include/intx/intx.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,7 @@ inline constexpr uint128& operator-=(uint128& x, uint128 y) noexcept
return x = x - y;
}

inline uint128& operator*=(uint128& x, uint128 y) noexcept
inline constexpr uint128& operator*=(uint128& x, uint128 y) noexcept
{
return x = x * y;
}
Expand Down Expand Up @@ -1806,7 +1806,7 @@ inline constexpr uint<N>& operator>>=(uint<N>& x, const T& y) noexcept
}


inline uint256 addmod(const uint256& x, const uint256& y, const uint256& mod) noexcept
inline constexpr uint256 addmod(const uint256& x, const uint256& y, const uint256& mod) noexcept
{
// Fast path for mod >= 2^192, with x and y at most slightly bigger than mod.
// This is always the case when x and y are already reduced modulo mod.
Expand Down Expand Up @@ -1840,7 +1840,7 @@ inline uint256 addmod(const uint256& x, const uint256& y, const uint256& mod) no
return udivrem(n, mod).rem;
}

inline uint256 mulmod(const uint256& x, const uint256& y, const uint256& mod) noexcept
inline constexpr uint256 mulmod(const uint256& x, const uint256& y, const uint256& mod) noexcept
{
return udivrem(umul(x, y), mod).rem;
}
Expand Down
10 changes: 10 additions & 0 deletions test/unittests/test_uint256.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ constexpr decltype(&addmod) addmod_impls[] = {

TEST(uint256, addmod)
{
static_assert(
addmod(0xdce049946eccbbf77ed1e8e2a3c89e15a8e897df2194150700f5096dea864cdb_u256,
0x397dd0df188eaffbf5216c6be56fe49002fbdc23b95a58a60f69e56f6f87f424_u256,
0xf0f9d0006f7b450e8f73f621a6ca3b56_u128) == 0x7533da49e8c499530049fbf08733976b_u128);

for (auto&& impl : addmod_impls)
{
const auto x = 0xab0f4afc4c78548d4c30e1ab3449e3_u128;
Expand Down Expand Up @@ -208,6 +213,11 @@ TEST(uint256, addmod_ec2)

TEST(uint256, mulmod)
{
static_assert(
mulmod(0x4028c97ce32bf74a3a3137956b07a5a699ca8422bdf672f547_u256,
0x8c9f09b6227ba6542a97343c679e1d11d8bfa29228c18615c2_u256,
0xf0f9d0006f7b450e8f73f621a6ca3b56_u128) == 0xca283039a2ad0dbd3d60fbadb29e9c7a_u128);

const auto x = 0xab0f4afc4c78548d4c30e1ab3449e3_u128;
const auto y = 0xf0a4485af15508e448cdddb0d1301664_u128;
const auto mod = 0xf0f9d0006f7b450e8f73f621a6ca3b56_u128;
Expand Down