I've seen mulmod used in Mikhail Vladimirov's Math in Solidity series:

function fullMul(uint256 x, uint256 y) public pure returns (uint256 l, uint256 h) {
    uint256 mm = mulmod(x, y, uint256(-1));
    l = x * y;
    h = mm - l;
    if (mm < l) h -= 1;

What does it do exactly?


As per the Solidity cheatsheet, mulmod is a function available at the global scope.

mulmod(uint x, uint y, uint k) returns (uint): compute (x * y) % k where the multiplication is performed with arbitrary precision and does not wrap around at 2**256. Assert that k != 0 starting from version 0.5.0.

Some examples:

  1. mulmod(3, 4, 5) is equal to 2.
  2. mulmod(2**256 - 1, 1, type(uint256).max) is equal to 0.
  3. mulmod(2**255, 2**255, type(uint256).max) is equal to 1.

Notice that even if 2**255 * 2**255 overflows, the contract call doesn't revert in Solidity v0.8.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.