0

How do I compute the multiplication of two uint256 so the result doesn't overflow?

In the end, this multiplication is an intermediate step within a larger operation, in case this extra piece of info helps.

Fyi, I'm not looking to change the order of the operations nor remove any padding.

uint256 a = 10864869065949319007600000000000000000000;
uint256 b = 3300000000000000000000000000000000000000;
uint256 c = 10859952502829164007600000000000000000000;

uint256 result = (a * b) / c;

The overflow occurs in (a * b).

Assembly is more than welcomed if it produces the expected result. Thanks!

2
  • One way is to divide them separately by c and then multiply to get the result like result = (((a * 1e18) / c) * ((b * 1e18) / c)) / 1e18. But, you've mentioned that you're not looking to change the order of the operations, therefore it's not valid in that case. Commented Apr 23 at 12:40
  • 1
    Yeah, and dividing before multiplying comes with precision loss also, something that I'm trying to avoid @SYEDASADKAZMI
    – dNyrM
    Commented Apr 23 at 12:58

1 Answer 1

0

Using https://github.com/SimonSuckut/Solidity_Uint512/blob/main/contracts/Uint512.sol

(uint r0, uint r1) = a.mul256x256(b);
uint result = r0.div512x256(r1, c);
2
  • Great. Does it give the accurate result without precision loss ? Commented Apr 23 at 22:25
  • 1
    Correct. Tested it out already. @SYEDASADKAZMI
    – dNyrM
    Commented Apr 24 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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